diff options
Diffstat (limited to 'sca-java-1.x/branches/sca-java-M2/sca/services')
542 files changed, 48622 insertions, 0 deletions
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/.ruleset new file mode 100644 index 0000000000..70a035bc01 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/.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-M2/sca/services/bindings/binding.axis2/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/LICENSE.txt new file mode 100644 index 0000000000..0084319535 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, serviceDefinition 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-M2/sca/services/bindings/binding.axis2/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/pom.xml new file mode 100755 index 0000000000..e9d32c7f9c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/pom.xml @@ -0,0 +1,163 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.bindings</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>axis2</artifactId> + <name>Apache Tuscany Binding for Axis2</name> + <description>Implementation of the SCA Web Services binding using Axis2.</description> + + <repositories> + <!-- ws zones repos is for woden --> + <repository> + <id>apache.ws.zones</id> + <name>Apache WS zones Repository</name> + <url>http://ws.zones.apache.org/repository/</url> + <layout>legacy</layout> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>wsdl</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <!-- A hack to bring in databinding-axiom transitively --> + <dependency> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>databinding-axiom</artifactId> + <version>${sca.version}</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + </dependency> + + <!-- Axis2 1.1 release --> + + <dependency> + <groupId>org.apache.axis2</groupId> + <artifactId>axis2-kernel</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-api</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-impl</artifactId> + </dependency> + + <dependency> + <groupId>incubator-woden</groupId> + <artifactId>woden</artifactId> + <version>1.0.0M6</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>woodstox</groupId> + <artifactId>wstx-asl</artifactId> + </dependency> + + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <version>1.1</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>org.apache.ws.commons.neethi</groupId> + <artifactId>neethi</artifactId> + <version>2.0</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>org.apache.ws.commons.schema</groupId> + <artifactId>XmlSchema</artifactId> + </dependency> + + <dependency> + <groupId>commons-httpclient</groupId> + <artifactId>commons-httpclient</artifactId> + <version>3.0.1</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> + <version>1.4</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>backport-util-concurrent</groupId> + <artifactId>backport-util-concurrent</artifactId> + <version>2.2</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>commons-codec</groupId> + <artifactId>commons-codec</artifactId> + <version>1.3</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>httpcomponents-httpcore</groupId> + <artifactId>jakarta-httpcore</artifactId> + <version>4.0-alpha2</version> + <scope>runtime</scope> + </dependency> + + <!-- end Axis2 1.1 release --> + + <!-- test dependencies --> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>test</artifactId> + <version>${sca.version}</version> + <scope>test</scope> + </dependency> + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/assembly/axis2.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/assembly/axis2.xml new file mode 100644 index 0000000000..7c835caa5c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/assembly/axis2.xml @@ -0,0 +1,38 @@ +<?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. +--> +<assembly> + <id>bin</id> + <includeBaseDirectory>false</includeBaseDirectory> + <formats> + <format>zip</format> + <format>tar.gz</format> + </formats> + + <dependencySets> + <dependencySet> + <outputDirectory>extension</outputDirectory> + <includes> + <include>org.apache.tuscany.bindings:axis2</include> + </includes> + <fileMode>644</fileMode> + </dependencySet> + </dependencySets> +</assembly> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2AsyncTargetInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2AsyncTargetInvoker.java new file mode 100644 index 0000000000..0cf3976f37 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2AsyncTargetInvoker.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.axis2; + +import java.lang.reflect.InvocationTargetException; + +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.soap.SOAPFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.OperationClient; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; + +public class Axis2AsyncTargetInvoker extends Axis2TargetInvoker { + + protected static final OMElement RESPONSE = null; + + private InboundWire wire; + private Object messageId; + private Axis2ReferenceCallbackTargetInvoker callbackInvoker; + + public Axis2AsyncTargetInvoker(ServiceClient serviceClient, + QName wsdlOperationName, + Options options, + SOAPFactory soapFactory, + InboundWire wire) { + super(serviceClient, wsdlOperationName, options, soapFactory); + this.wire = wire; + } + + public Object invokeTarget(final Object payload) throws InvocationTargetException { + try { + Object[] args = (Object[])payload; + OperationClient operationClient = createOperationClient(args); + callbackInvoker.setCorrelationId(messageId); + Axis2ReferenceCallback callback = new Axis2ReferenceCallback(callbackInvoker); + operationClient.setCallback(callback); + + operationClient.execute(false); + + // REVIEW it seems ok to return null + return RESPONSE; + } catch (AxisFault e) { + throw new InvocationTargetException(e); + } + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + wire.addMapping(msg.getMessageId(), msg.getFromAddress()); + messageId = msg.getMessageId(); + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } + + public void setCallbackTargetInvoker(Axis2ReferenceCallbackTargetInvoker callbackInvoker) { + this.callbackInvoker = callbackInvoker; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingBuilder.java new file mode 100755 index 0000000000..1090be874d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingBuilder.java @@ -0,0 +1,208 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +import javax.wsdl.Port; +import javax.wsdl.PortType; + +import org.apache.axiom.om.OMElement; +import org.apache.axis2.AxisFault; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.tuscany.binding.axis2.util.TuscanyAxisConfigurator; +import org.apache.tuscany.idl.wsdl.InterfaceWSDLIntrospector; +import org.apache.tuscany.idl.wsdl.WSDLServiceContract; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.BindingBuilderExtension; +import org.apache.tuscany.spi.host.ServletHost; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.IncompatibleServiceContractException; + +/** + * Builds a {@link org.osoa.sca.annotations.Service} or {@link org.apache.tuscany.spi.component.Reference} configured + * with the Axis2 binding + * + * @version $Rev$ $Date$ + */ +public class Axis2BindingBuilder extends BindingBuilderExtension<WebServiceBinding> { + private static final String OM_DATA_BINDING = OMElement.class.getName(); + + private ServletHost servletHost; + + private ConfigurationContext configContext; + + private WorkContext workContext; + + private InterfaceWSDLIntrospector introspector; + + public Axis2BindingBuilder() { + initAxis(); + } + + @Autowire(required = false) + public void setServletHost(ServletHost servletHost) { + this.servletHost = servletHost; + } + + /** + * @param introspector the introspector to set + */ + @Autowire + public void setIntrospector(InterfaceWSDLIntrospector introspector) { + this.introspector = introspector; + } + + @Autowire + public void setWorkContext(WorkContext workContext) { + this.workContext = workContext; + } + + @SuppressWarnings("unchecked") + public Service build( + CompositeComponent parent, + BoundServiceDefinition<WebServiceBinding> serviceDefinition, + DeploymentContext deploymentContext) { + + try { + // Set the default databinding + ServiceContract<?> outboundContract = serviceDefinition.getServiceContract(); + if (WSDLServiceContract.class.isInstance(outboundContract)) { + outboundContract.setDataBinding(OM_DATA_BINDING); + } + + // FIXME: We need to define how the WSDL PortType is honored in the case that + // both the binding.ws and interface.wsdl are in place. + // The WSDL portType from the WSDL Port decides the incoming SOAP message format + // There are also cases that interface.java is used. + + ServiceContract<?> inboundContract = null; + WebServiceBinding wsBinding = serviceDefinition.getBinding(); + Port port = wsBinding.getWSDLPort(); + if (port == null) { + // FIXME: [rfeng] No WSDL is referenced by binding.ws, we need to create one from + // the outbound service contract if it's JavaServiceContract + inboundContract = outboundContract; + } + + PortType portType = wsBinding.getWSDLPort().getBinding().getPortType(); + inboundContract = introspector.introspect(portType); + + // FIXME: + inboundContract.setInterfaceClass(serviceDefinition.getServiceContract().getInterfaceClass()); + inboundContract.setDataBinding(OM_DATA_BINDING); + inboundContract.setCallbackName(serviceDefinition.getServiceContract().getCallbackName()); + + try { + wireService.checkCompatibility(inboundContract, outboundContract, true); + } catch (IncompatibleServiceContractException e) { + throw new Axis2BindingBuilderRuntimeException(e); + } + + Service service = new Axis2Service(serviceDefinition.getName(), outboundContract, parent, wireService, wsBinding, + servletHost, configContext, workContext); + service.setBindingServiceContract(inboundContract); + + return service; + + } catch (InvalidServiceContractException e) { + throw new Axis2BindingBuilderRuntimeException(e); + } + } + + @SuppressWarnings("unchecked") + public Reference build( + CompositeComponent parent, + BoundReferenceDefinition<WebServiceBinding> boundReferenceDefinition, + DeploymentContext deploymentContext) { + + try { + // Set the default binding + ServiceContract<?> inboundContract = boundReferenceDefinition.getServiceContract(); + if (WSDLServiceContract.class.isInstance(inboundContract)) { + inboundContract.setDataBinding(OM_DATA_BINDING); + } + + // FIXME: We need to define how the WSDL PortType is honored in the case that + // both the binding.ws and interface.wsdl are in place + // The WSDL portType from the WSDL Port decides the incoming SOAP message format + + ServiceContract<?> outboundContract = inboundContract; + WebServiceBinding wsBinding = boundReferenceDefinition.getBinding(); + Port port = wsBinding.getWSDLPort(); + if (port == null) { + // FIXME: [rfeng] No WSDL is referenced by binding.ws, we need to create one from + // the inbound service contract if it's JavaServiceContract + outboundContract = inboundContract; + } + PortType portType = port.getBinding().getPortType(); + outboundContract = introspector.introspect(portType); + + // Set the default databinding + outboundContract.setDataBinding(OM_DATA_BINDING); + + try { + wireService.checkCompatibility(inboundContract, outboundContract, true); + } catch (IncompatibleServiceContractException e) { + throw new Axis2BindingBuilderRuntimeException(e); + } + + Reference reference = new Axis2Reference(boundReferenceDefinition.getName(), parent, wireService, wsBinding, + inboundContract, workContext); + reference.setBindingServiceContract(outboundContract); + + return reference; + + } catch (InvalidServiceContractException e) { + throw new Axis2BindingBuilderRuntimeException(e); + } + } + + protected Class<WebServiceBinding> getBindingType() { + return WebServiceBinding.class; + } + + protected void initAxis() { + // TODO: Fix classloader switching. See TUSCANY-647 + // TODO: also consider having a system component wrapping the Axis2 ConfigContext + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + ClassLoader scl = getClass().getClassLoader(); + try { + if (tccl != scl) { + Thread.currentThread().setContextClassLoader(scl); + } + try { + this.configContext = new TuscanyAxisConfigurator().getConfigurationContext(); + } catch (AxisFault e) { + throw new BuilderConfigException(e); + } + } finally { + if (tccl != scl) { + Thread.currentThread().setContextClassLoader(tccl); + } + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingBuilderRuntimeException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingBuilderRuntimeException.java new file mode 100644 index 0000000000..a5743668a4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingBuilderRuntimeException.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.binding.axis2; + + +/** + * Base class for Exceptions raised during the loading process. Loader implementations should throw a subclass of this + * to indicate the actual problem. + * + * @version $Rev$ $Date$ + */ +public class Axis2BindingBuilderRuntimeException extends Axis2BindingRunTimeException { + private static final long serialVersionUID = -7459051598906813461L; + private String resourceURI; + + public Axis2BindingBuilderRuntimeException() { + } + + public Axis2BindingBuilderRuntimeException(String message) { + super(message); + } + + public Axis2BindingBuilderRuntimeException(String message, Throwable cause) { + super(message, cause); + } + + public Axis2BindingBuilderRuntimeException(Throwable cause) { + super(cause); + } + + /** + * Returns the location of the resource that was being loaded. + * + * @return the location of the resource that was being loaded + */ + public String getResourceURI() { + return resourceURI; + } + + /** + * Sets the location of the resource that was being loaded. + * + * @param resourceURI the location of the resource that was being loaded + */ + public void setResourceURI(String resourceURI) { + this.resourceURI = resourceURI; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingRunTimeException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingRunTimeException.java new file mode 100644 index 0000000000..cd957c2ec6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2BindingRunTimeException.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.binding.axis2; + +import org.apache.tuscany.api.TuscanyRuntimeException; + +/** + * Denotes an error creating a new object instance + * + * @version $Rev$ $Date$ + */ +public class Axis2BindingRunTimeException extends TuscanyRuntimeException { + private static final long serialVersionUID = -6423113430265944499L; + + public Axis2BindingRunTimeException() { + super(); + } + + public Axis2BindingRunTimeException(String message) { + super(message); + } + + public Axis2BindingRunTimeException(String message, Throwable cause) { + super(message, cause); + } + + public Axis2BindingRunTimeException(Throwable cause) { + super(cause); + } + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2CallbackInvocationHandler.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2CallbackInvocationHandler.java new file mode 100644 index 0000000000..4a9e054237 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2CallbackInvocationHandler.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.binding.axis2; + +import java.util.Map; + +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.AbstractOutboundInvocationHandler; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.TargetInvoker; + +public class Axis2CallbackInvocationHandler extends AbstractOutboundInvocationHandler { + + private InboundWire inboundWire; + private Object messageId; + private Object correlationId; + + public Axis2CallbackInvocationHandler(InboundWire inboundWire) { + this.inboundWire = inboundWire; + } + + public Object invoke(Operation operation, Object[] args) throws Throwable { + Object targetAddress = inboundWire.retrieveMapping(correlationId); + if (targetAddress == null) { + throw new AssertionError("No from address associated with message id [" + correlationId + "]"); + } + //TODO optimize as this is slow in local invocations + Map<Operation<?>, OutboundInvocationChain> sourceCallbackInvocationChains = + inboundWire.getSourceCallbackInvocationChains(targetAddress); + OutboundInvocationChain chain = sourceCallbackInvocationChains.get(operation); + TargetInvoker invoker = chain.getTargetInvoker(); + return invoke(chain, invoker, args); + } + + // This must be called before invoke + public void setMessageId(Object messageId) { + this.messageId = messageId; + } + + // This must be called before invoke + public void setCorrelationId(Object correlationId) { + this.correlationId = correlationId; + } + + protected Object getFromAddress() { + return (inboundWire.getContainer() == null) ? null : inboundWire.getContainer().getName(); + } + + protected Object getMessageId() { + return messageId; + } + + protected Object getCorrelationId() { + return correlationId; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2OneWayTargetInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2OneWayTargetInvoker.java new file mode 100644 index 0000000000..a85c57313f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2OneWayTargetInvoker.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +import java.lang.reflect.InvocationTargetException; + +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.soap.SOAPFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.OperationClient; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; + +public class Axis2OneWayTargetInvoker extends Axis2TargetInvoker { + + protected static final OMElement RESPONSE = null; + + public Axis2OneWayTargetInvoker(ServiceClient serviceClient, + QName wsdlOperationName, + Options options, + SOAPFactory soapFactory) { + + super(serviceClient, wsdlOperationName, options, soapFactory); + } + + public Object invokeTarget(final Object payload) throws InvocationTargetException { + try { + Object[] args = (Object[])payload; + OperationClient operationClient = createOperationClient(args); + + operationClient.execute(false); + + // REVIEW it seems ok to return null + return RESPONSE; + } catch (AxisFault e) { + throw new InvocationTargetException(e); + } catch (Throwable t) { + throw new Axis2BindingRunTimeException(t); + } + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2Reference.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2Reference.java new file mode 100755 index 0000000000..53ae1ae51e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2Reference.java @@ -0,0 +1,187 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +import java.util.Collection; + +import javax.wsdl.Definition; +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.soap.SOAPFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.description.AxisService; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.tuscany.binding.axis2.util.TuscanyAxisConfigurator; +import org.apache.tuscany.binding.axis2.util.WebServiceOperationMetaData; +import org.apache.tuscany.binding.axis2.util.WebServicePortMetaData; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.extension.ReferenceExtension; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; + +/** + * Axis2Reference uses Axis2 to invoke a remote web service + */ +public class Axis2Reference<T> extends ReferenceExtension { + + private WebServicePortMetaData wsPortMetaData; + private ServiceClient serviceClient; + + // private WorkContext workContext; + + @SuppressWarnings("unchecked") + public Axis2Reference(String theName, + CompositeComponent parent, + WireService wireService, + WebServiceBinding wsBinding, + ServiceContract contract, + WorkContext workContext) { + super(theName, (Class<T>)contract.getInterfaceClass(), parent, wireService); + try { + Definition wsdlDefinition = wsBinding.getWSDLDefinition(); + wsPortMetaData = + new WebServicePortMetaData(wsdlDefinition, wsBinding.getWSDLPort(), wsBinding.getURI(), false); + serviceClient = createServiceClient(wsdlDefinition, wsPortMetaData); + // this.workContext = workContext; + } catch (AxisFault e) { + throw new Axis2BindingRunTimeException(e); + } + } + + public TargetInvoker createTargetInvoker(ServiceContract contract, Operation operation) { + Axis2TargetInvoker invoker; + try { + boolean isOneWay = operation.isNonBlocking(); + invoker = createOperationInvoker(serviceClient, operation, wsPortMetaData, false, isOneWay); + } catch (AxisFault e) { + throw new Axis2BindingRunTimeException(e); + } + return invoker; + } + + public TargetInvoker createAsyncTargetInvoker(OutboundWire wire, Operation operation) { + Axis2AsyncTargetInvoker invoker; + try { + // FIXME: SDODataBinding needs to pass in TypeHelper and classLoader + // as parameters. + invoker = + (Axis2AsyncTargetInvoker)createOperationInvoker(serviceClient, + operation, + wsPortMetaData, + true, + false); + // FIXME: This makes the (BIG) assumption that there is only one + // callback method + // Relaxing this assumption, however, does not seem to be trivial, + // it may depend on knowledge + // of what actual callback method was invoked by the service at the + // other end + Operation callbackOperation = findCallbackOperation(); + Axis2CallbackInvocationHandler invocationHandler = + new Axis2CallbackInvocationHandler(inboundWire); + Axis2ReferenceCallbackTargetInvoker callbackInvoker = + new Axis2ReferenceCallbackTargetInvoker(callbackOperation, inboundWire, invocationHandler); + invoker.setCallbackTargetInvoker(callbackInvoker); + } catch (AxisFault e) { + throw new Axis2BindingRunTimeException(e); + } + return invoker; + } + + private Operation findCallbackOperation() { + ServiceContract contract = inboundWire.getServiceContract(); + Operation callbackOperation = null; + Collection callbackOperations = contract.getCallbackOperations().values(); + if (callbackOperations.size() != 1) { + throw new Axis2BindingRunTimeException("Can only handle one callback operation"); + } else { + callbackOperation = (Operation)callbackOperations.iterator().next(); + } + return callbackOperation; + } + + /** + * Create an Axis2 ServiceClient + */ + private ServiceClient createServiceClient(Definition wsdlDefinition, WebServicePortMetaData wsPortMetaData) + throws AxisFault { + + TuscanyAxisConfigurator tuscanyAxisConfigurator = new TuscanyAxisConfigurator(); + ConfigurationContext configurationContext = tuscanyAxisConfigurator.getConfigurationContext(); + QName serviceQName = wsPortMetaData.getServiceName(); + String portName = wsPortMetaData.getPortName().getLocalPart(); + AxisService axisService = + AxisService.createClientSideAxisService(wsdlDefinition, serviceQName, portName, new Options()); + return new ServiceClient(configurationContext, axisService); + } + + /** + * Create and configure an Axis2TargetInvoker for each operations + */ + private Axis2TargetInvoker createOperationInvoker(ServiceClient serviceClient, + Operation m, + WebServicePortMetaData wsPortMetaData, + boolean hasCallback, + boolean isOneWay) throws AxisFault { + SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory(); + String portTypeNS = wsPortMetaData.getPortTypeName().getNamespaceURI(); + + String methodName = m.getName(); + + WebServiceOperationMetaData operationMetaData = wsPortMetaData.getOperationMetaData(methodName); + + Options options = new Options(); + options.setTo(new EndpointReference(wsPortMetaData.getEndpoint())); + options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE); + + String wsdlOperationName = operationMetaData.getBindingOperation().getOperation().getName(); + + String soapAction = wsPortMetaData.getOperationMetaData(wsdlOperationName).getSOAPAction(); + if (soapAction != null && soapAction.length() > 1) { + options.setAction(soapAction); + } + + options.setTimeOutInMilliSeconds(5 * 60 * 1000); + + QName wsdlOperationQName = new QName(portTypeNS, wsdlOperationName); + + Axis2TargetInvoker invoker; + if (hasCallback) { + invoker = + new Axis2AsyncTargetInvoker(serviceClient, wsdlOperationQName, options, soapFactory, + inboundWire); + } else if (isOneWay) { + invoker = new Axis2OneWayTargetInvoker(serviceClient, wsdlOperationQName, options, soapFactory); + } else { + invoker = new Axis2TargetInvoker(serviceClient, wsdlOperationQName, options, soapFactory); + } + + return invoker; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ReferenceCallback.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ReferenceCallback.java new file mode 100644 index 0000000000..d6bb1a0290 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ReferenceCallback.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.binding.axis2; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.axiom.om.OMElement; +import org.apache.axis2.client.async.AsyncResult; +import org.apache.axis2.client.async.Callback; +import org.apache.axis2.context.MessageContext; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; + +public class Axis2ReferenceCallback extends Callback { + + private Axis2ReferenceCallbackTargetInvoker targetInvoker; + + public Axis2ReferenceCallback(Axis2ReferenceCallbackTargetInvoker targetInvoker) { + this.targetInvoker = targetInvoker; + } + + public void onComplete(AsyncResult result) { + MessageContext responseMC = result.getResponseMessageContext(); + OMElement responseOM = responseMC.getEnvelope().getBody().getFirstElement(); + try { + targetInvoker.invokeTarget(new Object[] {responseOM}); + } catch (InvocationTargetException e) { + // FIXME what is the appropriate exception here? + throw new InvocationRuntimeException(e); + } + } + + public void setComplete(boolean complete) { + super.setComplete(complete); + } + + public void onError(Exception e) { + throw new InvocationRuntimeException(e); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ReferenceCallbackTargetInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ReferenceCallbackTargetInvoker.java new file mode 100644 index 0000000000..87f9b5654b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ReferenceCallbackTargetInvoker.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.binding.axis2; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; + +public class Axis2ReferenceCallbackTargetInvoker implements TargetInvoker { + + private Operation operation; + private InboundWire inboundWire; + private Object correlationId; + private boolean cacheable; + Axis2CallbackInvocationHandler invocationHandler; + + public Axis2ReferenceCallbackTargetInvoker(Operation operation, + InboundWire inboundWire, + Axis2CallbackInvocationHandler invocationHandler) { + + this.operation = operation; + this.inboundWire = inboundWire; + this.invocationHandler = invocationHandler; + } + + public Object invokeTarget(final Object payload) throws InvocationTargetException { + invocationHandler.setMessageId(null); + invocationHandler.setCorrelationId(correlationId); + Object[] args; + if (payload != null && !payload.getClass().isArray()) { + args = new Object[]{payload}; + } else { + args = (Object[]) payload; + } + try { + return invocationHandler.invoke(operation, args); + } catch(Throwable t) { + t.printStackTrace(); + throw new InvocationTargetException(t); + } + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (InvocationTargetException e) { + msg.setBodyWithFault(e.getCause()); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } + + public boolean isCacheable() { + return cacheable; + } + + public void setCacheable(boolean cacheable) { + this.cacheable = cacheable; + } + + public boolean isOptimizable() { + return isCacheable(); // we only need to check if the scopes are correct + } + + public Axis2ReferenceCallbackTargetInvoker clone() throws CloneNotSupportedException { + Axis2ReferenceCallbackTargetInvoker invoker = (Axis2ReferenceCallbackTargetInvoker) super.clone(); + invoker.operation = this.operation; + invoker.inboundWire = this.inboundWire; + invoker.correlationId = this.correlationId; + invoker.cacheable = this.cacheable; + invoker.invocationHandler = this.invocationHandler; + return invoker; + } + + public void setCorrelationId(Object correlationId) { + this.correlationId = correlationId; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2Service.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2Service.java new file mode 100755 index 0000000000..47c9d8308a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2Service.java @@ -0,0 +1,290 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; + +import javax.wsdl.Definition; +import javax.wsdl.Operation; +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import org.apache.axiom.soap.SOAPFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.description.AxisOperation; +import org.apache.axis2.description.AxisService; +import org.apache.axis2.description.Parameter; +import org.apache.axis2.description.WSDL11ToAxisServiceBuilder; +import org.apache.axis2.description.WSDLToAxisServiceBuilder; +import org.apache.axis2.engine.MessageReceiver; +import org.apache.axis2.wsdl.WSDLConstants; +import org.apache.axis2.wsdl.WSDLConstants.WSDL20_2004Constants; +import org.apache.tuscany.binding.axis2.util.WebServicePortMetaData; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.host.ServletHost; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.InvocationChain; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageId; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; +import org.osoa.sca.annotations.Destroy; + +/** + * An implementation of a {@link ServiceExtension} configured with the Axis2 + * binding + * + * @version $Rev$ $Date$ + */ +public class Axis2Service extends ServiceExtension { + private ServiceContract<?> serviceContract; + + private ServletHost servletHost; + + private ConfigurationContext configContext; + + private WebServiceBinding binding; + + private WorkContext workContext; + + private Map<MessageId, InvocationContext> invCtxMap = new HashMap<MessageId, InvocationContext>(); + + private String serviceName; + + public Axis2Service(String theName, + ServiceContract<?> serviceContract, + CompositeComponent parent, + WireService wireService, + WebServiceBinding binding, + ServletHost servletHost, + ConfigurationContext configContext, + WorkContext workContext) { + + super(theName, serviceContract.getInterfaceClass(), parent, wireService); + + this.serviceContract = serviceContract; + this.binding = binding; + this.servletHost = servletHost; + this.configContext = configContext; + this.workContext = workContext; + this.serviceName = theName; + } + + public void start() { + super.start(); + + try { + configContext.getAxisConfiguration().addService(createAxisService(binding)); + } catch (AxisFault e) { + throw new Axis2BindingRunTimeException(e); + } + + Axis2ServiceServlet servlet = new Axis2ServiceServlet(); + servlet.init(configContext); + configContext.setContextRoot(getName()); + servletHost.registerMapping("/" + getName(), servlet); + } + + @Destroy + public void stop() { + servletHost.unregisterMapping("/" + getName()); + try { + configContext.getAxisConfiguration().removeService(getName()); + } catch (AxisFault e) { + throw new Axis2BindingRunTimeException(e); + } + super.stop(); + } + + private AxisService createAxisService(WebServiceBinding wsBinding) throws AxisFault { + Definition definition = wsBinding.getWSDLDefinition(); + WebServicePortMetaData wsdlPortInfo = + new WebServicePortMetaData(definition, wsBinding.getWSDLPort(), null, false); + + // TODO investigate if this is 20 wsdl what todo? + WSDLToAxisServiceBuilder builder = + new WSDL11ToAxisServiceBuilder(definition, wsdlPortInfo.getServiceName(), wsdlPortInfo.getPort() + .getName()); + builder.setServerSide(true); + AxisService axisService = builder.populateService(); + + axisService.setName(this.getName()); + axisService.setServiceDescription("Tuscany configured AxisService for service: '" + this.getName() + + "'"); + + // Use the existing WSDL + Parameter wsdlParam = new Parameter(WSDLConstants.WSDL_4_J_DEFINITION, null); + wsdlParam.setValue(definition); + axisService.addParameter(wsdlParam); + Parameter userWSDL = new Parameter("useOriginalwsdl", "true"); + axisService.addParameter(userWSDL); + + PortType wsdlPortType = wsdlPortInfo.getPortType(); + for (Object o : wsdlPortType.getOperations()) { + Operation wsdlOperation = (Operation)o; + String operationName = wsdlOperation.getName(); + QName operationQN = new QName(definition.getTargetNamespace(), operationName); + + org.apache.tuscany.spi.model.Operation<?> op = serviceContract.getOperations().get(operationName); + + MessageReceiver msgrec = null; + boolean opIsNonBlocking = op.isNonBlocking(); + if (serviceContract.getCallbackName() != null) { + msgrec = new Axis2ServiceInOutAsyncMessageReceiver(this, op, workContext); + } else if (opIsNonBlocking) { + msgrec = new Axis2ServiceInMessageReceiver(this, op); + } else { + msgrec = new Axis2ServiceInOutSyncMessageReceiver(this, op); + } + + AxisOperation axisOp = axisService.getOperation(operationQN); + if (opIsNonBlocking) { + axisOp.setMessageExchangePattern(WSDL20_2004Constants.MEP_URI_IN_ONLY); + } else { + axisOp.setMessageExchangePattern(WSDL20_2004Constants.MEP_URI_IN_OUT); + } + axisOp.setMessageReceiver(msgrec); + } + + return axisService; + } + + public Object invokeTarget(org.apache.tuscany.spi.model.Operation<?> op, Object[] args) + throws InvocationTargetException { + InvocationChain chain = inboundWire.getInvocationChains().get(op); + Interceptor headInterceptor = chain.getHeadInterceptor(); + if (headInterceptor == null) { + try { + // short-circuit the dispatch and invoke the target directly + if (chain.getTargetInvoker() == null) { + throw new AssertionError("No target invoker [" + chain.getOperation().getName() + "]"); + } + return chain.getTargetInvoker().invokeTarget(args); + } catch (InvocationTargetException e) { + // the cause was thrown by the target so throw it + throw e; + } + } else { + Object messageId = workContext.getCurrentMessageId(); + workContext.setCurrentMessageId(null); + Object correlationId = workContext.getCurrentCorrelationId(); + workContext.setCurrentCorrelationId(null); + + Message msg = new MessageImpl(); + msg.setTargetInvoker(chain.getTargetInvoker()); + msg.setFromAddress(getFromAddress()); + if (messageId == null) { + messageId = new MessageId(); + } + msg.setMessageId(messageId); + msg.setCorrelationId(correlationId); + msg.setBody(args); + Message resp; + // dispatch the wire down the chain and get the response + // TODO http://issues.apache.org/jira/browse/TUSCANY-777 + ClassLoader oldtccl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + resp = headInterceptor.invoke(msg); + } finally { + Thread.currentThread().setContextClassLoader(oldtccl); + } + Object body = resp.getBody(); + if (resp.isFault()) { + throw new InvocationTargetException((Throwable)body); + } + return body; + } + } + + protected Object getFromAddress() { + return this.serviceName; + } + + /** + * Get the Method from an interface matching the WSDL operation name + */ + protected Method getMethod(Class<?> serviceInterface, String operationName) { + // Note: this doesn't support overloaded operations + Method[] methods = serviceInterface.getMethods(); + for (Method m : methods) { + if (m.getName().equals(operationName)) { + return m; + } + // tolerate WSDL with capatalized operation name + StringBuilder sb = new StringBuilder(operationName); + sb.setCharAt(0, Character.toLowerCase(sb.charAt(0))); + if (m.getName().equals(sb.toString())) { + return m; + } + } + throw new BuilderConfigException("no operation named " + operationName + + " found on service interface: " + + serviceInterface.getName()); + } + + public TargetInvoker createCallbackTargetInvoker(ServiceContract contract, + org.apache.tuscany.spi.model.Operation operation) { + + return new Axis2ServiceCallbackTargetInvoker(workContext, this); + } + + public void addMapping(MessageId msgId, InvocationContext invCtx) { + this.invCtxMap.put(msgId, invCtx); + } + + public InvocationContext retrieveMapping(MessageId msgId) { + return this.invCtxMap.get(msgId); + } + + public void removeMapping(MessageId msgId) { + this.invCtxMap.remove(msgId); + } + + protected class InvocationContext { + public MessageContext inMessageContext; + + public org.apache.tuscany.spi.model.Operation<?> operation; + + public SOAPFactory soapFactory; + + public CountDownLatch doneSignal; + + public InvocationContext(MessageContext messageCtx, + org.apache.tuscany.spi.model.Operation<?> operation, + SOAPFactory soapFactory, + CountDownLatch doneSignal) { + this.inMessageContext = messageCtx; + this.operation = operation; + this.soapFactory = soapFactory; + this.doneSignal = doneSignal; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceCallbackTargetInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceCallbackTargetInvoker.java new file mode 100644 index 0000000000..ca7812e01b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceCallbackTargetInvoker.java @@ -0,0 +1,114 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.soap.SOAPEnvelope; +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.engine.AxisEngine; +import org.apache.axis2.util.Utils; +import org.apache.tuscany.binding.axis2.Axis2Service.InvocationContext; +import org.apache.tuscany.binding.axis2.Axis2AsyncTargetInvoker; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageId; +import org.apache.tuscany.spi.wire.TargetInvoker; + +public class Axis2ServiceCallbackTargetInvoker implements TargetInvoker { + + private Axis2Service service; + + private MessageId currentCorrelationId; + + public Axis2ServiceCallbackTargetInvoker(WorkContext workContext, Axis2Service service) { + this.service = service; + } + + public Object invokeTarget(final Object payload) throws InvocationTargetException { + try { + // Use current correlation id as index to retrieve inv context + InvocationContext invCtx = service.retrieveMapping(this.currentCorrelationId); + + MessageContext outMC = Utils.createOutMessageContext(invCtx.inMessageContext); + outMC.getOperationContext().addMessageContext(outMC); + + OMElement responseOM = null; + if (payload != null && !payload.getClass().isArray()) { + responseOM = (OMElement)payload; + } else { + responseOM = (OMElement)((Object[])payload)[0]; + } + SOAPEnvelope soapEnvelope = invCtx.soapFactory.getDefaultEnvelope(); + soapEnvelope.getBody().addChild(responseOM); + outMC.setEnvelope(soapEnvelope); + outMC.getOperationContext().setProperty(Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE); + + AxisEngine engine = + new AxisEngine(invCtx.inMessageContext.getOperationContext().getServiceContext().getConfigurationContext()); + engine.send(outMC); + + invCtx.doneSignal.countDown(); + + service.removeMapping(this.currentCorrelationId); + } catch (AxisFault e) { + throw new InvocationTargetException(e); + } catch(Throwable t) { + throw new Axis2BindingRunTimeException(t); + } + + return Axis2AsyncTargetInvoker.RESPONSE; + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + this.currentCorrelationId = (MessageId)msg.getCorrelationId(); + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } + + public Axis2ServiceCallbackTargetInvoker clone() throws CloneNotSupportedException { + try { + return (Axis2ServiceCallbackTargetInvoker)super.clone(); + } catch (CloneNotSupportedException e) { + // will not happen + return null; + } + } + + public boolean isCacheable() { + return true; + } + + public void setCacheable(boolean cacheable) { + + } + + public boolean isOptimizable() { + return false; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInMessageReceiver.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInMessageReceiver.java new file mode 100644 index 0000000000..3b1b0d25e4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInMessageReceiver.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.binding.axis2; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.axiom.om.OMElement; +import org.apache.axis2.AxisFault; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.receivers.AbstractInMessageReceiver; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; + +public class Axis2ServiceInMessageReceiver extends AbstractInMessageReceiver { + + protected Operation<?> operation; + + private Axis2Service axis2Service; + + public Axis2ServiceInMessageReceiver(Axis2Service service, Operation<?> operation) { + this.axis2Service = service; + this.operation = operation; + } + + public Axis2ServiceInMessageReceiver() { + + } + + @Override + public void invokeBusinessLogic(MessageContext inMC) throws AxisFault { + try { + OMElement requestOM = inMC.getEnvelope().getBody().getFirstElement(); + Object[] args = new Object[] {requestOM}; + + axis2Service.invokeTarget(operation, args); + + } catch (InvocationTargetException e) { + Throwable t = e.getCause(); + if (t instanceof Exception) { + throw AxisFault.makeFault((Exception)t); + } + throw new InvocationRuntimeException(e); + } catch (Throwable t) { + if (t instanceof Exception) { + throw AxisFault.makeFault((Exception)t); + } + throw new Axis2BindingRunTimeException(t); + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInOutAsyncMessageReceiver.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInOutAsyncMessageReceiver.java new file mode 100644 index 0000000000..f83862399c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInOutAsyncMessageReceiver.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.axis2; + +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.CountDownLatch; + +import org.apache.axiom.om.OMElement; +import org.apache.axis2.AxisFault; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.receivers.AbstractMessageReceiver; +import org.apache.tuscany.binding.axis2.Axis2Service.InvocationContext; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.MessageId; + +public class Axis2ServiceInOutAsyncMessageReceiver extends AbstractMessageReceiver { + + private Operation<?> operation; + + private WorkContext workContext; + + private Axis2Service service; + + public Axis2ServiceInOutAsyncMessageReceiver(Axis2Service service, + Operation operation, + WorkContext workContext) { + this.operation = operation; + this.workContext = workContext; + this.service = service; + } + + public Axis2ServiceInOutAsyncMessageReceiver() { + } + + public final void receive(final MessageContext messageCtx) { + try { + // Create a new message id and hand it to + // JDKInboundInvocationHandler + // via work context + MessageId messageId = new MessageId(); + workContext.setCurrentMessageId(messageId); + // Now use message id as index to context to be used by callback + // target invoker + CountDownLatch doneSignal = new CountDownLatch(1); + InvocationContext invCtx = + service.new InvocationContext(messageCtx, operation, getSOAPFactory(messageCtx), doneSignal); + service.addMapping(messageId, invCtx); + + invokeBusinessLogic(messageCtx); + + try { + doneSignal.await(); + } catch(InterruptedException e) { + e.printStackTrace(); + } + } catch (AxisFault e) { + // log.error(e); + } + } + + public void invokeBusinessLogic(MessageContext inMC) throws AxisFault { + try { + OMElement requestOM = inMC.getEnvelope().getBody().getFirstElement(); + Object[] args = new Object[] {requestOM}; + service.invokeTarget(operation, args); + } catch (InvocationTargetException e) { + Throwable t = e.getCause(); + if (t instanceof Exception) { + throw AxisFault.makeFault((Exception)t); + } + throw new InvocationRuntimeException(e); + } catch (Exception e) { + throw AxisFault.makeFault(e); + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInOutSyncMessageReceiver.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInOutSyncMessageReceiver.java new file mode 100644 index 0000000000..4522632d9f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceInOutSyncMessageReceiver.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.axis2; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.soap.SOAPEnvelope; +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.receivers.AbstractInOutSyncMessageReceiver; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; + +public class Axis2ServiceInOutSyncMessageReceiver extends AbstractInOutSyncMessageReceiver { + + protected Operation<?> operation; + + private Axis2Service axis2Service; + + public Axis2ServiceInOutSyncMessageReceiver(Axis2Service service, Operation<?> operation) { + this.axis2Service = service; + this.operation = operation; + } + + public Axis2ServiceInOutSyncMessageReceiver() { + + } + + @Override + public void invokeBusinessLogic(MessageContext inMC, MessageContext outMC) throws AxisFault { + try { + OMElement requestOM = inMC.getEnvelope().getBody().getFirstElement(); + Object[] args = new Object[] {requestOM}; + + OMElement responseOM = (OMElement)axis2Service.invokeTarget(operation, args); + + SOAPEnvelope soapEnvelope = getSOAPFactory(inMC).getDefaultEnvelope(); + soapEnvelope.getBody().addChild(responseOM); + outMC.setEnvelope(soapEnvelope); + outMC.getOperationContext().setProperty(Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE); + + } catch (InvocationTargetException e) { + e.printStackTrace(); + Throwable t = e.getCause(); + if (t instanceof Exception) { + throw AxisFault.makeFault((Exception)t); + } + throw new InvocationRuntimeException(e); + } catch (Exception e) { + e.printStackTrace(); + throw AxisFault.makeFault(e); + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceServlet.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceServlet.java new file mode 100644 index 0000000000..cab5b28ee7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2ServiceServlet.java @@ -0,0 +1,207 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Set; +import java.util.Vector; + +import javax.servlet.RequestDispatcher; +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.transport.http.AxisServlet; + +/** + * This overrides the servlet init of the AxisServlet so Tuscany can use + * a single Axis2 ConfigurationContext instance shared between AxisServlet + * instances for each SCA service with a ws binding. + * TODO: need to review if thats really what we want to be doing + */ +public class Axis2ServiceServlet extends AxisServlet { + + private static final long serialVersionUID = 1L; + + private static final ServletConfig DUMMY_CONFIG = createDummyServletConfig(); + + private boolean inited; + + public void init(ConfigurationContext configContext) { + this.configContext = configContext; + try { + super.init(DUMMY_CONFIG); + } catch (ServletException e) { + throw new RuntimeException(e); + } + } + + /** + * We've setup the Servlet by passing in a ConfigurationContext on our init method + * override this method to just return that + */ + @Override + protected ConfigurationContext initConfigContext(ServletConfig config) throws ServletException { + return this.configContext; + } + + /** + * The AxisServlet gets NPE during init without a ServletConfig so this is a mocked up one to prevent that. + */ + private static ServletConfig createDummyServletConfig() { + ServletConfig sc = new ServletConfig() { + + public String getServletName() { + return "TuscanyAxis2DummyServlet"; + } + + public ServletContext getServletContext() { + return new ServletContext() { + + public ServletContext getContext(String uripath) { + return null; + } + + public int getMajorVersion() { + return 0; + } + + public int getMinorVersion() { + return 0; + } + + public String getMimeType(String file) { + return null; + } + + public Set getResourcePaths(String path) { + return Collections.emptySet(); + } + + public URL getResource(String path) throws MalformedURLException { + if("/".equals(path)) { + // HACK: To avoid NPE + return new URL("/axis2"); + } + return null; + } + + public InputStream getResourceAsStream(String path) { + return null; + } + + public RequestDispatcher getRequestDispatcher(String path) { + return null; + } + + public RequestDispatcher getNamedDispatcher(String arg0) { + return null; + } + + public Servlet getServlet(String arg0) throws ServletException { + return null; + } + + public Enumeration getServlets() { + return null; + } + + public Enumeration getServletNames() { + return null; + } + + public void log(String arg0) { + } + + public void log(Exception arg0, String arg1) { + } + + public void log(String arg0, Throwable arg1) { + } + + public String getRealPath(String arg0) { + return null; + } + + public String getServerInfo() { + return null; + } + + public String getInitParameter(String arg0) { + return null; + } + + public Enumeration getInitParameterNames() { + return null; + } + + public Object getAttribute(String arg0) { + return null; + } + + public Enumeration getAttributeNames() { + return null; + } + + public void setAttribute(String arg0, Object arg1) { + } + + public void removeAttribute(String arg0) { + } + + public String getServletContextName() { + return null; + } + }; + } + + public String getInitParameter(String arg0) { + return null; + } + + public Enumeration getInitParameterNames() { + return new Vector().elements(); + } + }; + return sc; + } + + @Override + protected void service(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + // HACK: Get the correct context root which is not available during init() call + if (!inited) { + synchronized (configContext) { + configContext.setContextRoot(request.getContextPath()); + inited = true; + } + } + super.service(request, response); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2TargetInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2TargetInvoker.java new file mode 100755 index 0000000000..175f995c76 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/Axis2TargetInvoker.java @@ -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. + */ +package org.apache.tuscany.binding.axis2; + +import java.lang.reflect.InvocationTargetException; + +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.soap.SOAPBody; +import org.apache.axiom.soap.SOAPEnvelope; +import org.apache.axiom.soap.SOAPFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.OperationClient; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.wsdl.WSDLConstants; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; + +/** + * Axis2TargetInvoker uses an Axis2 OperationClient to invoke a remote web service + */ +public class Axis2TargetInvoker implements TargetInvoker { + + private QName wsdlOperationName; + + private Options options; + + private SOAPFactory soapFactory; + + private ServiceClient serviceClient; + + public Axis2TargetInvoker(ServiceClient serviceClient, QName wsdlOperationName, Options options, + SOAPFactory soapFactory) { + this.wsdlOperationName = wsdlOperationName; + this.options = options; + this.soapFactory = soapFactory; + this.serviceClient = serviceClient; + } + + /** + * Invoke a WS operation + * + * @param payload + * @return + * @throws InvocationTargetException + */ + public Object invokeTarget(final Object payload) throws InvocationTargetException { + try { + Object[] args = (Object[]) payload; + OperationClient operationClient = createOperationClient(args); + + operationClient.execute(true); + + MessageContext responseMC = operationClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); + return responseMC.getEnvelope().getBody().getFirstElement(); + + } catch (AxisFault e) { + throw new InvocationTargetException(e); + } + + } + + protected OperationClient createOperationClient(Object[] args) throws AxisFault { + SOAPEnvelope env = soapFactory.getDefaultEnvelope(); + if (args != null && args.length > 0) { + SOAPBody body = env.getBody(); + for (Object bc : args) { + if (bc instanceof OMElement) { + body.addChild((OMElement) bc); + } else { + throw new IllegalArgumentException( + "Can't handle mixed payloads betweem OMElements and other types."); + } + } + } + MessageContext requestMC = new MessageContext(); + requestMC.setEnvelope(env); + // Axis2 operationClients can not be shared so create a new one for each request + OperationClient operationClient = serviceClient.createClient(wsdlOperationName); + operationClient.setOptions(options); + operationClient.addMessageContext(requestMC); + return operationClient; + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } + + public Axis2TargetInvoker clone() throws CloneNotSupportedException { + try { + return (Axis2TargetInvoker) super.clone(); + } catch (CloneNotSupportedException e) { + // will not happen + return null; + } + } + + public boolean isCacheable() { + return true; + } + + public void setCacheable(boolean cacheable) { + + } + + public boolean isOptimizable() { + return false; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/WebServiceBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/WebServiceBinding.java new file mode 100755 index 0000000000..6d4ec6eaf9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/WebServiceBinding.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.axis2; + + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import org.apache.tuscany.spi.model.Binding; + +/** + * Represents a Celtix binding configuration in an assembly + * + * @version $Rev$ $Date$ + */ +public class WebServiceBinding extends Binding { + + private Definition definition; + private Port port; + private Service service; + //private String portURI; + private String uri; + public WebServiceBinding(Definition definition, Port port, String uri, String portURI, Service service) { + this.definition = definition; + this.port = port; + this.uri = uri; + //this.portURI = portURI; + this.service = service; + } + + public Port getWSDLPort() { + return port; + } + + public Service getWSDLService() { + return service; + } + + public void setWSDLPort(Port value) { + port = value; + } + + public Definition getWSDLDefinition() { + return definition; + } + + public void setWSDLDefinition(Definition def) { + definition = def; + } + + // public void setPortURI(String uri) { + // portURI = uri; + // } + + public String getURI() { + return uri; + } + + public void setURI(String theUri) { + this.uri = theUri; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/WebServiceBindingLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/WebServiceBindingLoader.java new file mode 100755 index 0000000000..5535dbb5c2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/WebServiceBindingLoader.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.axis2; + +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; + +import java.io.IOException; +import java.util.Collection; + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistry; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; +import org.osoa.sca.annotations.Constructor; +import org.osoa.sca.annotations.Scope; + +/** + * Parses a <code>WebServiceBinding</code> entry in an assembly XML file + * + * @version $Rev$ $Date$ + */ +@Scope("MODULE") +@SuppressWarnings("deprecation") +public class WebServiceBindingLoader extends LoaderExtension<WebServiceBinding> { + public static final QName BINDING_WS = new QName(XML_NAMESPACE_1_0, "binding.ws"); + + private WSDLDefinitionRegistry wsdlDefinitionRegistry; + + @Constructor( { "loaderRegistry", "wsdlDefinitionRegistry" }) + public WebServiceBindingLoader(@Autowire LoaderRegistry loaderRegistry, + @Autowire WSDLDefinitionRegistry wsdlDefinitionRegistry) { + super(loaderRegistry); + this.wsdlDefinitionRegistry = wsdlDefinitionRegistry; + } + + public QName getXMLType() { + return BINDING_WS; + } + + public WebServiceBinding load(CompositeComponent parent, XMLStreamReader reader, DeploymentContext deploymentContext) + throws XMLStreamException, LoaderException { + // not sure what uri was here ? String uri = reader.getAttributeValue(null, "uri"); + String uri = null; + String endpoint = reader.getAttributeValue(null, "endpoint"); + String wsdlLocation = reader.getAttributeValue(null, "location"); + LoaderUtil.skipToEndElement(reader); + try { + return createBinding(uri, endpoint, wsdlLocation, deploymentContext); + } catch (Exception e) { + throw new LoaderException(e); + } + + } + + @SuppressWarnings("unchecked") + private WebServiceBinding createBinding(String uri, String endpoint, String wsdlLocation, DeploymentContext deploymentContext) + throws WSDLException, IOException, LoaderException { + // Get the WSDL port namespace and name + if (uri == null && endpoint != null) { + int h = endpoint.indexOf('#'); + String serviceName; + String portName; + + String namespace = endpoint.substring(0, h); + String fragment = endpoint.substring(h + 1); + if (fragment.startsWith("wsdl.endpoint(") && fragment.endsWith(")")) { + fragment = fragment.substring(14, fragment.length() - 1); + int slash = fragment.indexOf('/'); + if (slash != -1) { + serviceName = fragment.substring(0, slash); + portName = fragment.substring(slash + 1); + } else { + serviceName = null; + portName = fragment; + } + } else { + serviceName = null; + portName = fragment; + } + // FIXME need to find out how to get wsdl and what context to use --- terrible hack attack! + if (null == wsdlLocation) { + throw new Axis2BindingRunTimeException( + "Failed to determine wsdl location on binding. Try specifying 'location' attribute on binding."); + } + Definition definition = + wsdlDefinitionRegistry.loadDefinition(namespace+" "+wsdlLocation, deploymentContext.getClassLoader()); + + Port thePort = null; + Service service = null; + // Find the port with the given name + for (Service serv : (Collection<Service>) definition.getServices().values()) { + QName sqn = serv.getQName(); + if (serviceName != null && !serviceName.equals(sqn.getLocalPart())) { + continue; + } + + Port p = serv.getPort(portName); + if (p != null) { + service = serv; + thePort = p; + break; + } + } + if (thePort == null) { + throw new IllegalArgumentException("Cannot find WSDL port " + endpoint); + + } + return new WebServiceBinding(definition, thePort, uri, endpoint, service); + } + // FIXME: Find the first port? + throw new LoaderException("Web Service endpoint cannot be resolved: " + endpoint); + + } + +}
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/TuscanyAxisConfigurator.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/TuscanyAxisConfigurator.java new file mode 100755 index 0000000000..c0ef46fee3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/TuscanyAxisConfigurator.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.binding.axis2.util; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.ConfigurationContextFactory; +import org.apache.axis2.deployment.URLBasedAxisConfigurator; +import org.apache.axis2.engine.AxisConfigurator; + +/** + * Helps configure Axis2 from a resource in binding.axis2 instead of Axis2.xml + * <p/> TODO: Review: should there be a single global Axis + * ConfigurationContext + */ +public class TuscanyAxisConfigurator extends URLBasedAxisConfigurator implements AxisConfigurator { + + public TuscanyAxisConfigurator() throws AxisFault { + super(TuscanyAxisConfigurator.class.getResource("/org/apache/tuscany/binding/axis2/engine/config/axis2.xml"), null); + } + + public ConfigurationContext getConfigurationContext() throws AxisFault { + if (configContext == null) + configContext = ConfigurationContextFactory.createConfigurationContext(this); + return configContext; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/WebServiceOperationMetaData.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/WebServiceOperationMetaData.java new file mode 100755 index 0000000000..2a453bdf15 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/WebServiceOperationMetaData.java @@ -0,0 +1,491 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2.util; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import javax.wsdl.Binding; +import javax.wsdl.BindingInput; +import javax.wsdl.BindingOperation; +import javax.wsdl.BindingOutput; +import javax.wsdl.Input; +import javax.wsdl.Message; +import javax.wsdl.Operation; +import javax.wsdl.Output; +import javax.wsdl.Part; +import javax.wsdl.extensions.soap.SOAPBinding; +import javax.wsdl.extensions.soap.SOAPHeader; +import javax.wsdl.extensions.soap.SOAPOperation; +import javax.xml.namespace.QName; + +/** + * Metadata for a WSDL operation + */ +@SuppressWarnings({"all"}) +public class WebServiceOperationMetaData implements Serializable { + private static final long serialVersionUID = 2425306250256227724L; + + // WSDL Binding and BindingOperation + private Binding binding; + private BindingOperation bindingOperation; + // Fields to cache derived metadata + private transient Set<Part> inputHeaderParts; + private transient Set<Part> outputHeaderParts; + private transient String style; + private transient String use; + private transient String soapAction; + private transient List<Object> signature; + private String encoding; + private transient QName rpcOperationName; + + public WebServiceOperationMetaData(Binding binding, BindingOperation bindingOperation) { + this.binding = binding; + this.bindingOperation = bindingOperation; + } + + public WebServiceOperationMetaData(Binding binding, BindingOperation bindingOperation, String style, String use, + String encoding, + String soapAction) { + this.binding = binding; + this.bindingOperation = bindingOperation; + this.style = style; + this.use = use; + this.encoding = encoding; + this.soapAction = soapAction; + } + + public Set<Part> getInputHeaderParts() { + if (inputHeaderParts == null) { + // Build a set of header parts that we need to exclude + inputHeaderParts = new HashSet<Part>(); + BindingInput bindingInput = bindingOperation.getBindingInput(); + + if (bindingInput != null) { + Operation operation = bindingOperation.getOperation(); + javax.wsdl.Message message = operation.getInput().getMessage(); + List elements = bindingInput.getExtensibilityElements(); + for (Iterator i = elements.iterator(); i.hasNext();) { + Object extensibilityElement = i.next(); + Part part = getPartFromSOAPHeader(message, extensibilityElement); + if (part != null) { + inputHeaderParts.add(part); + } + } + } + } + return inputHeaderParts; + } + + public Set<Part> getOutputHeaderParts() { + if (outputHeaderParts == null) { + // Build a set of header parts that we need to exclude + outputHeaderParts = new HashSet<Part>(); + BindingOutput bindingOutput = bindingOperation.getBindingOutput(); + + if (bindingOutput != null) { + Operation operation = bindingOperation.getOperation(); + javax.wsdl.Message message = operation.getOutput().getMessage(); + List elements = bindingOutput.getExtensibilityElements(); + for (Iterator i = elements.iterator(); i.hasNext();) { + Object extensibilityElement = i.next(); + Part part = getPartFromSOAPHeader(message, extensibilityElement); + if (part != null) { + outputHeaderParts.add(part); + } + } + } + } + return outputHeaderParts; + } + + private Part getPartFromSOAPHeader(Message message, Object extensibilityElement) { + Part part = null; + if (extensibilityElement instanceof SOAPHeader) { + SOAPHeader soapHeader = (SOAPHeader) extensibilityElement; + QName msgName = soapHeader.getMessage(); + if (message.getQName().equals(msgName)) { + part = message.getPart(soapHeader.getPart()); + } + } else if (extensibilityElement instanceof SOAPHeader) { + SOAPHeader soapHeader = (SOAPHeader) extensibilityElement; + QName msgName = soapHeader.getMessage(); + if (message.getQName().equals(msgName)) { + part = message.getPart(soapHeader.getPart()); + } + } + return part; + } + + public String getStyle() { + if (style == null) { + SOAPOperation soapOperation = (SOAPOperation) WebServicePortMetaData + .getExtensibilityElement(bindingOperation.getExtensibilityElements(), + SOAPOperation.class); + if (soapOperation != null) { + style = soapOperation.getStyle(); + } + if (style == null) { + SOAPBinding soapBinding = WebServicePortMetaData + .getExtensibilityElement(binding.getExtensibilityElements(), SOAPBinding.class); + if (soapBinding != null) { + style = soapBinding.getStyle(); + } + } + if (style == null) { + style = "document"; + } + } + return style; + } + + /** + * Returns the SOAP action for the given operation. + */ + public String getSOAPAction() { + if (soapAction == null) { + final List wsdlBindingOperationExtensions = bindingOperation.getExtensibilityElements(); + final SOAPOperation soapOp = + WebServicePortMetaData.getExtensibilityElement(wsdlBindingOperationExtensions, SOAPOperation.class); + if (soapOp != null) { + soapAction = soapOp.getSoapActionURI(); + } + } + return soapAction; + } + + public QName getRPCOperationName() { + if (rpcOperationName == null) { + javax.wsdl.extensions.soap.SOAPBody soapBody = getSOAPBody(true); + String ns = + (soapBody != null) ? soapBody.getNamespaceURI() : binding.getPortType().getQName().getNamespaceURI(); + String name = bindingOperation.getOperation().getName(); + rpcOperationName = new QName(ns, name); + } + return rpcOperationName; + } + + private List<String> getSOAPBodyParts(boolean input) { + javax.wsdl.extensions.soap.SOAPBody soapBody = getSOAPBody(input); + if (soapBody != null) { + List parts = soapBody.getParts(); + if (parts != null) { + List<String> names = new ArrayList<String>(); + for (Iterator i = parts.iterator(); i.hasNext();) { + Object part = i.next(); + if (part instanceof String) { + names.add((String) part); + } else if (part instanceof Part) { + names.add(((Part) part).getName()); + } + } + return names; + } else { + return null; + } + } else { + return null; + } + } + + private javax.wsdl.extensions.soap.SOAPBody getSOAPBody(boolean input) { + List elements = null; + if (input) { + BindingInput bindingInput = bindingOperation.getBindingInput(); + if (bindingInput == null) { + return null; + } + elements = bindingInput.getExtensibilityElements(); + } else { + BindingOutput bindingOutput = bindingOperation.getBindingOutput(); + if (bindingOutput == null) { + return null; + } + elements = bindingOutput.getExtensibilityElements(); + } + javax.wsdl.extensions.soap.SOAPBody soapBody = WebServicePortMetaData.getExtensibilityElement(elements, + javax.wsdl.extensions.soap.SOAPBody.class); + return soapBody; + } + + /** + * Returns the use attribute + */ + public String getUse() { + if (use == null) { + javax.wsdl.extensions.soap.SOAPBody soapBody = getSOAPBody(true); + if (soapBody != null) { + use = soapBody.getUse(); + } + if (use == null) { + use = "literal"; + } + } + return use; + } + + @SuppressWarnings("unchecked") + public String getEncoding() { + if (encoding == null) { + javax.wsdl.extensions.soap.SOAPBody soapBody = getSOAPBody(true); + if (soapBody != null) { + List<String> styles = (List<String>) soapBody.getEncodingStyles(); + if (styles != null && !styles.isEmpty()) { + encoding = styles.get(0); + } + } + if (encoding == null) { + encoding = ""; + } + } + return encoding; + } + + public boolean isDocLitWrapped() { + boolean flag = getStyle().equals("document") && getUse().equals("literal"); + if (!flag) { + return false; + } + Message msg = getMessage(true); + if (msg == null) { + return false; + } + List parts = msg.getOrderedParts(null); + if (parts.size() != 1) { + return false; + } + Part part = (Part) parts.get(0); + QName element = part.getElementName(); + if (element == null) { + return false; + } + return element.getLocalPart().equals(bindingOperation.getOperation().getName()); + } + + /* + * public SOAPMediator createMediator(boolean serverMode) throws SOAPException { + * // create a new mediator for each invoke for thread-safety + * boolean rpcStyle = getStyle().equals("rpc"); boolean rpcEncoded = isEncoded(); + * + * SOAPMediator mediator = null; + * + * if (!rpcStyle) { // Document mediator = new SOAPDocumentLiteralMediatorImpl(this, serverMode); + * } else { if (!rpcEncoded) mediator = new + * SOAPRPCLiteralMediatorImpl(this, serverMode); // RPC-literal else mediator = + * new SOAPRPCEncodedMediatorImpl(this, serverMode); // RPC-encoded } + * return mediator; } + */ + + /** + * Get the operation signature from the WSDL operation + */ + public List<?> getOperationSignature() { + if (signature == null) { + signature = new ArrayList<Object>(); + + Operation operation = bindingOperation.getOperation(); + if (operation == null) { + return signature; + } + + final Input input = operation.getInput(); + if (input == null) { + return signature; + } + + String sstyle = getStyle(); + + if ("rpc".equals(sstyle)) { + Collection partNames = input.getMessage().getParts().values(); + for (Iterator i = partNames.iterator(); i.hasNext();) { + Part part = (Part) i.next(); + signature.add(part.getName()); + } + } else { + /* + * WS-I Basic Profile 1.1 4.7.6 Operation Signatures Definition: operation signature + * + * The profile defines the "operation signature" to be the fully qualified name of the child element of + * SOAP body of the SOAP input + * message described by an operation in a WSDL binding. + * + * In the case of rpc-literal binding, the operation name is used as a wrapper for the part accessors. + * In the document-literal case, designed so that they meet this requirement. + * + * An endpoint that supports multiple operations must unambiguously identify the operation being + * invoked based on the input message + * that it receives. This is only possible if all the operations specified in the wsdl:binding + * associated with an endpoint have a + * unique operation signature. + * + * R2710 The operations in a wsdl:binding in a DESCRIPTION MUST result in operation signatures that are + * different from one another. + */ + List<String> bodyParts = getSOAPBodyParts(true); + + Collection<?> parts = input.getMessage().getParts().values(); + // Exclude the parts to be transmitted in SOAP header + if (bodyParts == null) { + parts.removeAll(getInputHeaderParts()); + } + for (Iterator i = parts.iterator(); i.hasNext();) { + Part part = (Part) i.next(); + if (bodyParts == null) { + // All parts + QName elementName = part.getElementName(); + if (elementName == null) { + elementName = new QName("", part.getName()); + // TODO: [rfeng] throw new + // ServiceRuntimeException("Message part for + // document style must refer to an XSD element + // using a QName: " + part); + } + signature.add(elementName); + } else { + // "parts" in soap:body + if (bodyParts.contains(part.getName())) { + QName elementName = part.getElementName(); + if (elementName == null) { + elementName = new QName("", part.getName()); + // TODO: [rfeng] throw new + // ServiceRuntimeException("Message part for + // document style must refer to an XSD + // element using a QName: " + part); + } + signature.add(elementName); + } + + } + } + } + } + return signature; + } + + public Message getMessage(boolean isInput) { + Operation operation = bindingOperation.getOperation(); + if (operation == null) { + return null; + } + + if (isInput) { + final Input input = operation.getInput(); + return input == null ? null : input.getMessage(); + } else { + final Output output = operation.getOutput(); + return output == null ? null : output.getMessage(); + } + } + + public Part getInputPart(int index) { + Part part = null; + Message message = getMessage(true); + if (message == null) { + return part; + } + + List parts = message.getOrderedParts(null); + return (Part) parts.get(index); + + } + + public Part getOutputPart(int index) { + Part part = null; + Message message = getMessage(false); + if (message == null) { + return part; + } + + List parts = message.getOrderedParts(null); + return (Part) parts.get(index); + + } + + /** + * Get a list of indexes for each part in the SOAP body + * + * @param isInput + */ + public List<Integer> getBodyPartIndexes(boolean isInput) { + List<Integer> indexes = new ArrayList<Integer>(); + + Message message = getMessage(isInput); + if (message == null) { + return indexes; + } + + List<String> bodyParts = getSOAPBodyParts(isInput); + List parts = message.getOrderedParts(null); + Set headerParts = isInput ? getInputHeaderParts() : getOutputHeaderParts(); + + int index = 0; + for (Iterator i = parts.iterator(); i.hasNext(); index++) { + Part part = (Part) i.next(); + if (headerParts.contains(part)) { + continue; + } + if (bodyParts == null) { + // All parts + indexes.add(index); + } else { + // "parts" in soap:body + if (bodyParts.contains(part.getName())) { + indexes.add(index); + } + } + } + return indexes; + } + + /** + * Get the corresponding index for a part in the SOAP header by element name + * + * @param elementName + * @param isInput + */ + public int getHeaderPartIndex(QName elementName, boolean isInput) { + + Message message = getMessage(isInput); + if (message == null) { + return -1; + } + + List parts = message.getOrderedParts(null); + Set headerParts = isInput ? getInputHeaderParts() : getOutputHeaderParts(); + + int index = 0; + for (Iterator i = parts.iterator(); i.hasNext(); index++) { + Part part = (Part) i.next(); + // Test if the part is in header section + if (headerParts.contains(part) && elementName.equals(part.getElementName())) { + return index; + } + } + return -1; + } + + public BindingOperation getBindingOperation() { + return bindingOperation; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/WebServicePortMetaData.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/WebServicePortMetaData.java new file mode 100755 index 0000000000..a8d4f0f581 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/java/org/apache/tuscany/binding/axis2/util/WebServicePortMetaData.java @@ -0,0 +1,377 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import javax.wsdl.Binding; +import javax.wsdl.BindingOperation; +import javax.wsdl.Definition; +import javax.wsdl.Operation; +import javax.wsdl.Port; +import javax.wsdl.PortType; +import javax.wsdl.Service; +import javax.wsdl.extensions.soap.SOAPAddress; +import javax.wsdl.extensions.soap.SOAPBinding; +import javax.xml.namespace.QName; + +import org.apache.tuscany.idl.wsdl.WSDLServiceContract; + +/** + * Metadata for a WSDL port + * + */ +public class WebServicePortMetaData { + + private Service wsdlService; + private QName wsdlServiceName; + private Port wsdlPort; + private Binding wsdlBinding; + private QName wsdlPortName; + private PortType wsdlPortType; + private QName wsdlPortTypeName; + private String endpoint; + private boolean managed; + private List<WebServiceOperationMetaData> allOperationMetaData; + private WSDLServiceContract interfaceType; + + /** + * Constructor + * + * @param wsdlDefinition + */ + public WebServicePortMetaData(Definition wsdlDefinition, Port wsdlPort, String endpoint, boolean managed) { + + // Lookup the named port + this.wsdlPort = wsdlPort; + wsdlPortName = new QName(wsdlDefinition.getTargetNamespace(), wsdlPort.getName()); + Collection services = wsdlDefinition.getServices().values(); + for (Object serviceObj : services) { + Service service = (Service) serviceObj; + if (service.getPorts().containsValue(wsdlPort)) { + wsdlService = service; + wsdlServiceName = service.getQName(); + break; + } + } + + // Save the binding + wsdlBinding = wsdlPort.getBinding(); + if (wsdlBinding == null) { + throw new IllegalArgumentException("WSDL binding cannot be found for " + wsdlPortName); + } + + // Save the portType + wsdlPortType = wsdlBinding.getPortType(); + if (wsdlPortType == null) { + throw new IllegalArgumentException("WSDL portType cannot be found for " + wsdlPortName); + } + wsdlPortTypeName = wsdlPortType.getQName(); + + // Save the endpoint + this.endpoint = endpoint; + + // Track if this endpoint is managed or not + this.managed = managed; + } + + /** + * Constructor + * + * @param serviceName + * @param portName + * @param portTypeName + * @param endpoint + */ + public WebServicePortMetaData(QName serviceName, String portName, QName portTypeName, String endpoint) { + wsdlServiceName = serviceName; + wsdlPortName = new QName(serviceName.getNamespaceURI(), portName); + wsdlPortTypeName = portTypeName; + this.endpoint = endpoint; + } + + /** + * @return Returns the wsdlPort. + */ + public javax.wsdl.Port getPort() { + return wsdlPort; + } + + /** + * @return Returns the wsdlService. + */ + public QName getServiceName() { + return wsdlServiceName; + } + + /** + * @return Returns the wsdlService. + */ + public javax.wsdl.Service getService() { + return wsdlService; + } + + /** + * @return Returns the wsdlPortType. + */ + public PortType getPortType() { + return wsdlPortType; + } + + /** + * @return Returns the wsdlPortType. + */ + public QName getPortTypeName() { + return wsdlPortTypeName; + } + + /** + * @return Returns the wsdlBinding. + */ + public Binding getBinding() { + return wsdlBinding; + } + + /** + * @return Returns the wsdlPortName. + */ + public QName getPortName() { + return wsdlPortName; + } + + /** + * Returns the endpoint of a given port. + */ + public String getEndpoint() { + + // Return the specified endpoint + if (endpoint != null) { + return endpoint; + } + + // Find the target endpoint on the port + if (wsdlPort != null) { + final List wsdlPortExtensions = wsdlPort.getExtensibilityElements(); + for (final Object extension : wsdlPortExtensions) { + if (extension instanceof SOAPAddress) { + return ((SOAPAddress) extension).getLocationURI(); + } + } + } + + return null; + } + + /** + * Returns the SOAP binding style. + */ + public String getStyle() { + + // Find the binding style + String style = null; + if (wsdlBinding != null) { + final List wsdlBindingExtensions = wsdlBinding.getExtensibilityElements(); + SOAPBinding soapBinding = getExtensibilityElement(wsdlBindingExtensions, SOAPBinding.class); + if (soapBinding != null) { + style = soapBinding.getStyle(); + } + } + + // Default to document + return (style == null) ? "document" : style; + } + + /** + * Returns the use attribute + */ + public String getUse() { + List<WebServiceOperationMetaData> list = getAllOperationMetaData(); + return list.get(0).getUse(); + } + + /** + * Returns the encoding attribute + */ + public String getEncoding() { + List<WebServiceOperationMetaData> list = getAllOperationMetaData(); + return list.get(0).getEncoding(); + } + + /** + * @return Returns true if this is a managed web service. + */ + public boolean isManaged() { + return managed; + } + + /** + * Returns the first extensibility element of the given type. + * + * @param elements + * @param type + */ + public static <T> T getExtensibilityElement(List elements, Class<T> type) { + for (Object element : elements) { + if (type.isInstance(element)) { + return type.cast(element); + } + } + return null; + } + + /** + * Returns the extensibility elements of the given type. + * + * @param elements + * @param type + * @return List + */ + public static <T> List<T> getExtensibilityElements(List elements, Class<T> type) { + List<T> result = new ArrayList<T>(); + for (Object element : elements) { + if (type.isInstance(element)) { + result.add(type.cast(element)); + } + } + return result; + } + + /** + * Get the operation signature from the SOAP Body + * + * @return A list of QNames + */ + // public static List getOperationSignature(javax.xml.soap.SOAPBody body) { + // List signature = new ArrayList(); + // for (Iterator i = body.getChildElements(); i.hasNext();) { + // Object child = i.next(); + // if (child instanceof SOAPBodyElement) { + // Name name = ((SOAPBodyElement) child).getElementName(); + // QName qname = new QName(name.getURI(), name.getLocalName(), name.getPrefix()); + // signature.add(qname); + // } + // } + // return signature; + // } + // public static List getRPCOperationSignature(javax.xml.soap.SOAPBody body) { + // List signature = new ArrayList(); + // for (Iterator i = body.getChildElements(); i.hasNext();) { + // Object child = i.next(); + // if (child instanceof SOAPBodyElement) { + // SOAPBodyElement op = ((SOAPBodyElement) child); + // for (Iterator j = op.getChildElements(); j.hasNext();) { + // Object part = i.next(); + // if (part instanceof SOAPElement) { + // SOAPElement p = (SOAPElement) part; + // signature.add(p.getLocalName()); + // } + // } + // } + // } + // return signature; + // } + // public WebServiceOperationMetaData getOperationMetaData(javax.xml.soap.SOAPBody body) { + // List s1 = getOperationSignature(body); + // // List rpcParts = getRPCOperationSignature(body); + // for (Iterator it = getAllOperationMetaData().iterator(); it.hasNext();) { + // WebServiceOperationMetaData descriptor = (WebServiceOperationMetaData) it.next(); + // + // String style = descriptor.getStyle(); + // + // if (style.equals("document")) { + // List s2 = descriptor.getOperationSignature(); + // if (s1.equals(s2)) + // return descriptor; + // } else { + // QName op1 = (QName) s1.get(0); + // QName op2 = descriptor.getRPCOperationName(); + // if (op1.equals(op2)) { + // /* + // * // FIXME: [rfeng] We don't support method overloading + // * List partNames = getOperationSignature(binding, + // * bindingOperation); if (rpcParts.equals(partNames)) + // */ + // return descriptor; + // } + // } + // } + // return null; + // } + public List<WebServiceOperationMetaData> getAllOperationMetaData() { + if (allOperationMetaData == null) { + allOperationMetaData = new ArrayList<WebServiceOperationMetaData>(); + for (Iterator it = wsdlBinding.getBindingOperations().iterator(); it.hasNext();) { + final BindingOperation bindingOperation = (BindingOperation) it.next(); + if (bindingOperation.getOperation() != null) { + allOperationMetaData.add(new WebServiceOperationMetaData(wsdlBinding, bindingOperation)); + } + } + } + return allOperationMetaData; + } + + public WebServiceOperationMetaData getOperationMetaData(String operationName) { + StringBuilder sb = new StringBuilder(operationName); + sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); + String capatalizedOpName = sb.toString(); + + for (WebServiceOperationMetaData webServiceOperationMetaData : getAllOperationMetaData()) { + WebServiceOperationMetaData descriptor = (WebServiceOperationMetaData) webServiceOperationMetaData; + String opName = descriptor.getBindingOperation().getOperation().getName(); + + if (opName.equals(operationName) || opName.equals(capatalizedOpName)) { + return descriptor; + } + } + return null; + } + + /** + * Returns the WSDL service contract + * + * @return WSDLServiceContract + */ + public WSDLServiceContract getInterfaceType() { + return interfaceType; + } + + /** + * Get the WSDL operation name for a Java method name + */ + public String getWSDLOperationName(String methodName) { + StringBuilder sb = new StringBuilder(methodName); + sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); + String capatalizedOpName = sb.toString(); + for (Object o : wsdlPortType.getOperations()) { + Operation operation = (Operation) o; + String wsdlOpName = operation.getName(); + if (wsdlOpName.equals(methodName)) { + return wsdlOpName; + } + if (wsdlOpName.equals(capatalizedOpName)) { + return wsdlOpName; + } + } + return null; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/META-INF/sca/binding.axis2.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/META-INF/sca/binding.axis2.scdl new file mode 100644 index 0000000000..0eb56942f8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/META-INF/sca/binding.axis2.scdl @@ -0,0 +1,48 @@ +<?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.
+-->
+<!-- Axis2 based WebService binding extension -->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.binding.axis2.include">
+
+ <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2">
+ <group>org.apache.tuscany.sca.services.bindings</group>
+ <name>axis2</name>
+ <version>1.0-incubator-M2-SNAPSHOT</version>
+ </dependency>
+
+ <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2">
+ <group>org.apache.tuscany.sca.services.databinding</group>
+ <name>databinding-axiom</name>
+ <version>1.0-incubator-M2-SNAPSHOT</version>
+ </dependency>
+
+ <component name="webservice.bindingLoader">
+ <system:implementation.system class="org.apache.tuscany.binding.axis2.WebServiceBindingLoader" />
+ </component>
+
+ <component name="webservice.axis2.bindingBuilder">
+ <system:implementation.system class="org.apache.tuscany.binding.axis2.Axis2BindingBuilder" />
+ </component>
+
+ <!-- A workaround to handle inter-extension dependencies -->
+ <include name="idl.wsdl" scdlResource="META-INF/sca/idl.wsdl.scdl" />
+ <include name="databinding.axiom" scdlResource="META-INF/sca/databinding.axiom.scdl" />
+
+</composite>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..d14e850caf --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,49 @@ +<?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. +--> +<!-- Axis2 based WebService binding extension --> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + name="org.apache.tuscany.binding.axis2.WebServiceBinding"> + + <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <group>org.apache.tuscany.sca.services.bindings</group> + <name>axis2</name> + <version>1.0-incubator-M2-SNAPSHOT</version> + </dependency> + + <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <group>org.apache.tuscany.sca.services.databinding</group> + <name>databinding-axiom</name> + <version>1.0-incubator-M2-SNAPSHOT</version> + </dependency> + + <component name="webservice.bindingLoader"> + <system:implementation.system class="org.apache.tuscany.binding.axis2.WebServiceBindingLoader"/> + </component> + + <component name="webservice.axis2.bindingBuilder"> + <system:implementation.system class="org.apache.tuscany.binding.axis2.Axis2BindingBuilder"/> + </component> + + <!-- A workaround to handle inter-extension dependencies --> + <include name="idl.wsdl" scdlResource="META-INF/sca/idl.wsdl.scdl"/> + <include name="databinding.axiom" scdlResource="META-INF/sca/databinding.axiom.scdl"/> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/org/apache/tuscany/binding/axis2/engine/config/axis2.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/org/apache/tuscany/binding/axis2/engine/config/axis2.xml new file mode 100755 index 0000000000..84c86d6dfb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/main/resources/org/apache/tuscany/binding/axis2/engine/config/axis2.xml @@ -0,0 +1,302 @@ +<?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. +--> +<axisconfig name="AxisJava2.0"> + <!-- ================================================= --> + <!-- Parameters --> + <!-- ================================================= --> + <parameter name="hotdeployment" locked="false">false</parameter> + <parameter name="hotupdate" locked="false">false</parameter> + <parameter name="enableMTOM" locked="false">false</parameter> + <parameter name="enableSwA" locked="false">false</parameter> + + <!--Uncomment if you want to enable file caching for attachments --> + <!--parameter name="cacheAttachments" locked="false">true</parameter> + <parameter name="attachmentDIR" locked="false"></parameter> + <parameter name="sizeThreshold" locked="false">4000</parameter--> + + <!--This will give out the timout of the configuration contexts, in seconds--> + <parameter name="ConfigContextTimeoutInterval" locked="false">30</parameter> + + <!--During a fault, stacktrace can be sent with the fault message. The following flag will control --> + <!--that behaviour.--> + <parameter name="sendStacktraceDetailsWithFaults" locked="false">true</parameter> + + <!--If there aren't any information available to find out the fault reason, we set the message of the expcetion--> + <!--as the faultreason/Reason. But when a fault is thrown from a service or some where, it will be --> + <!--wrapped by different levels. Due to this the initial exception message can be lost. If this flag--> + <!--is set then, Axis2 tries to get the first exception and set its message as the faultreason/Reason.--> + <parameter name="DrillDownToRootCauseForFaultReason" locked="false">false</parameter> + + <parameter name="userName" locked="false">admin</parameter> + <parameter name="password" locked="false">axis2</parameter> + + <!--Following params will set the proper context paths for invocations. All the endpoints will have a commons context--> + <!--root which can configured using the following contextRoot parameter--> + <!--<parameter name="contextRoot" locked="false">axis2</parameter>--> + + <!--Our HTTP endpoints can handle both REST and SOAP. Following parameters can be used to distingiush those endpoints--> + <!--In case of a servlet, if you change this you have to manually change the settings of your servlet container to map this --> + <!--context path to proper Axis2 servlets--> + <!--<parameter name="servicePath" locked="false">services</parameter>--> + <!--<parameter name="restPath" locked="false">rest</parameter>--> + + + <!--Set the flag to true if you want to enable transport level session mangment--> + <parameter name="manageTransportSession" locked="false">false</parameter> + + <!--Following two parameters will be used to handle REST in Axis2. The default settings will make Axis2 to have two--> + <!--different endpoints, one for REST (AxisRESTServlet) one for SOAP message handling (AxisServlet). But following--> + <!--parameters help to tweak the message handling of two main servlets. --> + + <!-- If the enableRESTInAxis2MainServlet is true, then Axis2MainServlet will handle both SOAP and REST messages --> + <parameter name="enableRESTInAxis2MainServlet" locked="true">false</parameter> + + <!-- Following parameter will completely disable REST handling in both the servlets--> + <parameter name="disableREST" locked="true">false</parameter> + + <!-- This will disable the separate servlet we have for REST handling. --> + <parameter name="disableSeparateEndpointForREST" locked="true">false</parameter> + + <!-- If you have a frontend host which exposes this webservice using a different public URL --> + <!-- use this parameter to override autodetected url --> + <!--<parameter name="httpFrontendHostUrl" locked="false">https://someotherhost/context</parameter>--> + + + <!-- The way of adding listener to the system--> + <!-- <listener class="org.apache.axis2.ObserverIMPL">--> + <!-- <parameter name="RSS_URL" locked="false">http://127.0.0.1/rss</parameter>--> + <!-- </listener>--> + + <!-- ================================================= --> + <!-- Message Receivers --> + <!-- ================================================= --> + <!--This is the Deafult Message Receiver for the system , if you want to have MessageReceivers for --> + <!--all the other MEP implement it and add the correct entry to here , so that you can refer from--> + <!--any operation --> + <!--Note : You can ovride this for particular service by adding the same element with your requirement--> + <messageReceivers> + <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" + class="org.apache.tuscany.binding.axis2.Axis2ServiceInMessageReceiver"/> + <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" + class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/> + <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" + class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/> + <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" + class="org.apache.tuscany.binding.axis2.Axis2ServiceInOutAsyncMessageReceiver"/> + <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" + class="org.apache.tuscany.binding.axis2.Axis2ServiceInOutSyncMessageReceiver"/> + </messageReceivers> + <!-- ================================================= --> + <!-- Transport Ins --> + <!-- ================================================= --> + <transportReceiver name="http" + class="org.apache.axis2.transport.http.SimpleHTTPServer"> + <parameter name="port" locked="false">6060</parameter> + <!-- Here is the complete list of supported parameters (see example settings further below): + port: the port to listen on (default 6060) + hostname: if non-null, url prefix used in reply-to endpoint references (default null) + originServer: value of http Server header in outgoing messages (default "Simple-Server/1.1") + requestTimeout: value in millis of time that requests can wait for data (default 20000) + requestTcpNoDelay: true to maximize performance and minimize latency (default true) + false to minimize bandwidth consumption by combining segments + requestCoreThreadPoolSize: number of threads available for request processing (unless queue fills up) (default 25) + requestMaxThreadPoolSize: number of threads available for request processing if queue fills us (default 150) + note that default queue never fills up: see HttpFactory + threadKeepAliveTime: time to keep threads in excess of core size alive while inactive (default 180) + note that no such threads can exist with default unbounded request queue + threadKeepAliveTimeUnit: TimeUnit of value in threadKeepAliveTime (default SECONDS) (default SECONDS) + --> + <!-- <parameter name="hostname" locked="false">http://www.myApp.com/ws</parameter> --> + <!-- <parameter name="originServer" locked="false">My-Server/1.1</parameter> --> + <!-- <parameter name="requestTimeout" locked="false">10000</parameter> --> + <!-- <parameter name="requestTcpNoDelay" locked="false">false</parameter> --> + <!-- <parameter name="requestCoreThreadPoolSize" locked="false">50</parameter> --> + <!-- <parameter name="RequestMaxThreadPoolSize" locked="false">100</parameter> --> + <!-- <parameter name="threadKeepAliveTime" locked="false">240000</parameter> --> + <!-- <parameter name="threadKeepAliveTimeUnit" locked="false">MILLISECONDS</parameter> --> + </transportReceiver> + + <!--Uncomment this and configure as appropriate for JMS transport support, after setting up your JMS environment (e.g. ActiveMQ) + <transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener"> + <parameter name="myTopicConnectionFactory" locked="false"> + <parameter name="java.naming.factory.initial" locked="false">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter> + <parameter name="java.naming.provider.url" locked="false">tcp://localhost:61616</parameter> + <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">TopicConnectionFactory</parameter> + </parameter> + + <parameter name="myQueueConnectionFactory" locked="false"> + <parameter name="java.naming.factory.initial" locked="false">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter> + <parameter name="java.naming.provider.url" locked="false">tcp://localhost:61616</parameter> + <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">QueueConnectionFactory</parameter> + </parameter> + + <parameter name="default" locked="false"> + <parameter name="java.naming.factory.initial" locked="false">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter> + <parameter name="java.naming.provider.url" locked="false">tcp://localhost:61616</parameter> + <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">QueueConnectionFactory</parameter> + </parameter> + </transportReceiver>--> + + <!--Uncomment if you want to have SMTP transport support--> + <!--<transportReceiver name="mail" class="org.apache.axis2.transport.mail.SimpleMailListener">--> + <!--<parameter name="transport.mail.pop3.host" locked="false">127.0.0.1</parameter>--> + <!--<parameter name="transport.mail.pop3.user" locked="false">axis2</parameter>--> + <!--<parameter name="transport.mail.pop3.password" locked="false">axis2</parameter>--> + <!--<parameter name="transport.mail.pop3.port" locked="false">110</parameter>--> + <!--<parameter name="transport.mail.replyToAddress" locked="false">axis2@127.0.0.1</parameter>--> + <!--</transportReceiver>--> + + <transportReceiver name="tcp" + class="org.apache.axis2.transport.tcp.TCPServer"> + <parameter name="port" locked="false">6060</parameter> + <!--If you want to give your own host address for EPR generation--> + <!--uncommet following paramter , and set as you required.--> + <!--<parameter name="hostname" locked="false">tcp://myApp.com/ws</parameter>--> + </transportReceiver> + + <!-- ================================================= --> + <!-- Transport Outs --> + <!-- ================================================= --> + + <transportSender name="tcp" + class="org.apache.axis2.transport.tcp.TCPTransportSender"/> + <transportSender name="local" + class="org.apache.axis2.transport.local.LocalTransportSender"/> + <transportSender name="http" + class="org.apache.axis2.transport.http.CommonsHTTPTransportSender"> + <parameter name="PROTOCOL" locked="false">HTTP/1.1</parameter> + <parameter name="Transfer-Encoding" locked="false">chunked</parameter> + </transportSender> + <transportSender name="https" + class="org.apache.axis2.transport.http.CommonsHTTPTransportSender"> + <parameter name="PROTOCOL" locked="false">HTTP/1.1</parameter> + <parameter name="Transfer-Encoding" locked="false">chunked</parameter> + </transportSender> + + <!-- Commented out by Tuscany + <transportSender name="jms" + class="org.apache.axis2.transport.jms.JMSSender"/> + --> + + <!-- Uncomment this one with the appropriate papameters to enable the SMTP transport Receiver + <transportSender name="mailto" class="org.apache.axis2.transport.mail.MailTransportSender"> + <parameter name="transport.mail.smtp.host" locked="false">127.0.0.1</parameter> + <parameter name="transport.mail.smtp.user" locked="false">axis2</parameter> + <parameter name="transport.mail.smtp.password" locked="false">axis2</parameter> + <parameter name="transport.mail.smtp.port" locked="false">25</parameter> + </transportSender> + --> + + <!-- ================================================= --> + <!-- Global Modules --> + <!-- ================================================= --> + <!-- Comment this to disable Addressing --> + <!-- Commented out by Tuscany + <module ref="addressing"/> + --> + + <!--Configuring module , providing parameters for modules whether they refer or not--> + <!--<moduleConfig name="addressing">--> + <!--<parameter name="addressingPara" locked="false">N/A</parameter>--> + <!--</moduleConfig>--> + + <!-- ================================================= --> + <!-- Phases --> + <!-- ================================================= --> + <phaseOrder type="InFlow"> + <!-- System pre defined phases --> + <phase name="Transport"> + <handler name="RequestURIBasedDispatcher" + class="org.apache.axis2.engine.RequestURIBasedDispatcher"> + <order phase="Transport"/> + </handler> + <handler name="SOAPActionBasedDispatcher" + class="org.apache.axis2.engine.SOAPActionBasedDispatcher"> + <order phase="Transport"/> + </handler> + </phase> + <phase name="Security"/> + <phase name="PreDispatch"/> + <phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase"> + <handler name="AddressingBasedDispatcher" + class="org.apache.axis2.engine.AddressingBasedDispatcher"> + <order phase="Dispatch"/> + </handler> + + <handler name="SOAPMessageBodyBasedDispatcher" + class="org.apache.axis2.engine.SOAPMessageBodyBasedDispatcher"> + <order phase="Dispatch"/> + </handler> + <handler name="InstanceDispatcher" + class="org.apache.axis2.engine.InstanceDispatcher"> + <order phase="Dispatch"/> + </handler> + </phase> + <!-- System pre defined phases --> + <!-- After Postdispatch phase module author or or service author can add any phase he want --> + <phase name="OperationInPhase"/> + </phaseOrder> + <phaseOrder type="OutFlow"> + <!-- user can add his own phases to this area --> + <phase name="OperationOutPhase"/> + <!--system predefined phase--> + <!--these phase will run irrespective of the service--> + <phase name="PolicyDetermination"/> + <phase name="MessageOut"/> + <phase name="Security"/> + </phaseOrder> + <phaseOrder type="InFaultFlow"> + <phase name="PreDispatch"/> + <phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase"> + <handler name="RequestURIBasedDispatcher" + class="org.apache.axis2.engine.RequestURIBasedDispatcher"> + <order phase="Dispatch"/> + </handler> + + <handler name="SOAPActionBasedDispatcher" + class="org.apache.axis2.engine.SOAPActionBasedDispatcher"> + <order phase="Dispatch"/> + </handler> + + <handler name="AddressingBasedDispatcher" + class="org.apache.axis2.engine.AddressingBasedDispatcher"> + <order phase="Dispatch"/> + </handler> + + <handler name="SOAPMessageBodyBasedDispatcher" + class="org.apache.axis2.engine.SOAPMessageBodyBasedDispatcher"> + <order phase="Dispatch"/> + </handler> + <handler name="InstanceDispatcher" + class="org.apache.axis2.engine.InstanceDispatcher"> + <order phase="PostDispatch"/> + </handler> + </phase> + <!-- user can add his own phases to this area --> + <phase name="OperationInFaultPhase"/> + </phaseOrder> + <phaseOrder type="OutFaultFlow"> + <!-- user can add his own phases to this area --> + <phase name="OperationOutFaultPhase"/> + <phase name="PolicyDetermination"/> + <phase name="MessageOut"/> + </phaseOrder> +</axisconfig> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Axis2ReferenceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Axis2ReferenceTestCase.java new file mode 100755 index 0000000000..9605c50c51 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Axis2ReferenceTestCase.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +import java.lang.reflect.Type; +import java.net.URL; +import java.util.HashMap; + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.tuscany.idl.wsdl.WSDLServiceContract; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; +import org.easymock.EasyMock; +import org.xml.sax.InputSource; + +public class Axis2ReferenceTestCase extends TestCase { + + public void testInvokeService() throws Exception { + Axis2Reference axis2Reference = createAxis2Reference("testWebAppName", "testServiceName"); + Operation operation = new Operation<Type>("sayHi", null, null, null, false, null); + TargetInvoker targetInvoker = axis2Reference.createTargetInvoker(null, operation); + assertNotNull(targetInvoker); + } + + public void testAsyncTargetInvoker() throws Exception { + Axis2Reference axis2Reference = createAxis2Reference("testWebAppName", "testServiceName"); + //Create a mocked InboundWire, make the call of ServiceExtension.getInterface() returns a Class + InboundWire inboundWire = EasyMock.createNiceMock(InboundWire.class); + JavaServiceContract contract = new JavaServiceContract(Greeter.class); + contract.setCallbackClass(GreetingCallback.class); + Operation<Type> callbackOp = new Operation<Type>("sayHiCallback", null, null, null, true, null); + HashMap<String,Operation<Type>> callbackOps = new HashMap<String,Operation<Type>>(); + callbackOps.put("sayHiCallback", callbackOp); + contract.setCallbackOperations(callbackOps); + EasyMock.expect(inboundWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.replay(inboundWire); + + axis2Reference.setInboundWire(inboundWire); + Operation operation = new Operation<Type>("sayHi", null, null, null, true, null); + TargetInvoker asyncTargetInvoker = axis2Reference.createAsyncTargetInvoker(null, operation); + assertNotNull(asyncTargetInvoker); + } + + private Axis2Reference createAxis2Reference(String webAppName, String serviceName) throws Exception { + //Create WebServiceBinding + String wsdlLocation = "/wsdl/hello_world_doc_lit.wsdl"; + URL url = getClass().getResource(wsdlLocation); + assertNotNull("Could not find wsdl " + url.toString(), url); + + WSDLFactory factory = WSDLFactory.newInstance(); + WSDLReader reader = factory.newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + InputSource input = new InputSource(url.openStream()); + Definition wsdlDef = reader.readWSDL(url.toString(), input); + Service wsdlService = wsdlDef.getService(new QName("http://objectweb.org/hello_world_soap_http", + "SOAPService")); + Port port = wsdlService.getPort("SoapPort"); + WebServiceBinding wsBinding = new WebServiceBinding(wsdlDef, port, "uri", "portURI", wsdlService); + //Create a mocked WireService, make the call of ServiceExtension.getServiceInstance() returns a proxy instance. + WireService wireService = EasyMock.createNiceMock(WireService.class); + EasyMock.replay(wireService); + CompositeComponent parent = EasyMock.createNiceMock(CompositeComponent.class); + // TODO figure out what to do with the service contract + ServiceContract<?> contract = new WSDLServiceContract(); + contract.setInterfaceClass(Greeter.class); + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + return new Axis2Reference(serviceName, + parent, + wireService, + wsBinding, + contract, + workContext); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Axis2ServiceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Axis2ServiceTestCase.java new file mode 100755 index 0000000000..6669226547 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Axis2ServiceTestCase.java @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import javax.servlet.Servlet; +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +import org.xml.sax.InputSource; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.tuscany.binding.axis2.util.TuscanyAxisConfigurator; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.host.ServletHost; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +public class Axis2ServiceTestCase extends TestCase { + + public void testInvokeService() throws Exception { + TestServletHost tomcatHost = new TestServletHost(); + Axis2Service axis2Service = createAxis2Service("testServiceName", tomcatHost, false); + axis2Service.start(); + + if (true) return; + Servlet servlet = tomcatHost.getMapping("testWebAppName/services/testServiceName"); + assertNotNull(servlet); + + //Create mocked HttpRequest and HttpResponse object to test the Axis2Servlet + //To be done: + + } + + public void testAsyncMessageReceiver() throws Exception { + + TestServletHost tomcatHost = new TestServletHost(); + Axis2Service axis2Service = createAxis2Service("testServiceName", tomcatHost, true); + axis2Service.start(); + } + + private Axis2Service createAxis2Service(String serviceName, ServletHost tomcatHost, boolean callback) + throws Exception { + //Create WebServiceBinding + String wsdlLocation = "/wsdl/hello_world_doc_lit.wsdl"; + URL url = getClass().getResource(wsdlLocation); + assertNotNull("Could not find wsdl " + url.toString(), url); + + WSDLFactory factory = WSDLFactory.newInstance(); + WSDLReader reader = factory.newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + InputSource input = new InputSource(url.openStream()); + Definition wsdlDef = reader.readWSDL(url.toString(), input); + Service wsdlService = wsdlDef.getService(new QName("http://objectweb.org/hello_world_soap_http", + "SOAPService")); + Port port = wsdlService.getPort("SoapPort"); + WebServiceBinding wsBinding = new WebServiceBinding(wsdlDef, port, "uri", "portURI", wsdlService); + + //Create a mocked WireService, make the call of ServiceExtension.getServiceInstance() returns a proxy instance. + WireService wireService = EasyMock.createNiceMock(WireService.class); + wireService.createProxy(EasyMock.isA(InboundWire.class)); + EasyMock.expectLastCall().andReturn(null); + EasyMock.replay(wireService); + + //Create a mocked InboundWire, make the call of ServiceExtension.getInterface() returns a Class + InboundWire inboundWire = EasyMock.createNiceMock(InboundWire.class); + JavaServiceContract contract = new JavaServiceContract(Greeter.class); + Map<String, Operation<Type>> opMap = new HashMap<String, Operation<Type>>(); + for(Method m: Greeter.class.getMethods()) { + opMap.put(m.getName(), new Operation<Type>(m.getName(), null, null, null)); + } + contract.setOperations(opMap); + EasyMock.expect(inboundWire.getServiceContract()).andReturn(contract).anyTimes(); + if (callback) { + contract.setCallbackName(""); + } + EasyMock.replay(inboundWire); + + OutboundWire outboundWire = EasyMock.createNiceMock(OutboundWire.class); + Map<Operation<?>, OutboundInvocationChain> map = new HashMap<Operation<?>, OutboundInvocationChain>(); + EasyMock.expect(outboundWire.getInvocationChains()).andReturn(map).once(); + EasyMock.replay(outboundWire); + + TuscanyAxisConfigurator tuscanyAxisConfigurator = new TuscanyAxisConfigurator(); + ConfigurationContext configurationContext = tuscanyAxisConfigurator.getConfigurationContext(); + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + Axis2Service axis2Service = + new Axis2Service(serviceName, + contract, + null, + wireService, + wsBinding, + tomcatHost, + configurationContext, + workContext); + axis2Service.setInboundWire(inboundWire); + axis2Service.setOutboundWire(outboundWire); + + return axis2Service; + } + + protected class TestServletHost implements ServletHost { + private Map<String, Servlet> mappings = new HashMap<String, Servlet>(); + + public void registerMapping(String mapping, Servlet servlet) { + mappings.put(mapping, servlet); + } + + public void unregisterMapping(String mapping) { + } + + public Servlet getMapping(String mapping) { + return mappings.get(mapping); + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Greeter.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Greeter.java new file mode 100755 index 0000000000..39fccdadd3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/Greeter.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.axis2; + +public interface Greeter { + + String sayHi(); + + String greetMe(String requestType); + + void greetMeOneWay(String requestType); + + void greetMeWithCallback(String requestType); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/GreetingCallback.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/GreetingCallback.java new file mode 100644 index 0000000000..4c3b3304ea --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/java/org/apache/tuscany/binding/axis2/GreetingCallback.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.axis2; + +public interface GreetingCallback { + + void greetMeCallback(String greetMeResponse); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/resources/wsdl/hello_world_doc_lit.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/resources/wsdl/hello_world_doc_lit.wsdl new file mode 100755 index 0000000000..2f56217f88 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.axis2/src/test/resources/wsdl/hello_world_doc_lit.wsdl @@ -0,0 +1,169 @@ +<?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. +--> +<wsdl:definitions name="HelloWorld" targetNamespace="http://objectweb.org/hello_world_soap_http" + xmlns="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:tns="http://objectweb.org/hello_world_soap_http" + xmlns:x1="http://objectweb.org/hello_world_soap_http/types" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <wsdl:types> + <schema targetNamespace="http://objectweb.org/hello_world_soap_http/types" + xmlns="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://objectweb.org/hello_world_soap_http/types" + elementFormDefault="qualified"> + <simpleType name="MyStringType"> + <restriction base="string"> + <maxLength value="30" /> + </restriction> + </simpleType> + + <element name="sayHi"> + <complexType/> + </element> + <element name="sayHiResponse"> + <complexType> + <sequence> + <element name="responseType" type="string"/> + </sequence> + </complexType> + </element> + <element name="greetMe"> + <complexType> + <sequence> + <element name="requestType" type="tns:MyStringType"/> + </sequence> + </complexType> + </element> + <element name="greetMeResponse"> + <complexType> + <sequence> + <element name="responseType" type="string"/> + </sequence> + </complexType> + </element> + <element name="greetMeOneWay"> + <complexType> + <sequence> + <element name="requestType" type="string"/> + </sequence> + </complexType> + </element> + <element name="pingMe"> + <complexType/> + </element> + <element name="pingMeResponse"> + <complexType/> + </element> + <element name="faultDetail"> + <complexType> + <sequence> + <element name="minor" type="short"/> + <element name="major" type="short"/> + </sequence> + </complexType> + </element> + </schema> + </wsdl:types> + <wsdl:message name="sayHiRequest"> + <wsdl:part element="x1:sayHi" name="in"/> + </wsdl:message> + <wsdl:message name="sayHiResponse"> + <wsdl:part element="x1:sayHiResponse" name="out"/> + </wsdl:message> + <wsdl:message name="greetMeRequest"> + <wsdl:part element="x1:greetMe" name="in"/> + </wsdl:message> + <wsdl:message name="greetMeResponse"> + <wsdl:part element="x1:greetMeResponse" name="out"/> + </wsdl:message> + <wsdl:message name="greetMeOneWayRequest"> + <wsdl:part element="x1:greetMeOneWay" name="in"/> + </wsdl:message> + + <wsdl:portType name="Greeter"> + <wsdl:operation name="sayHi"> + <wsdl:input message="tns:sayHiRequest" name="sayHiRequest"/> + <wsdl:output message="tns:sayHiResponse" name="sayHiResponse"/> + </wsdl:operation> + + <wsdl:operation name="greetMe"> + <wsdl:input message="tns:greetMeRequest" name="greetMeRequest"/> + <wsdl:output message="tns:greetMeResponse" name="greetMeResponse"/> + </wsdl:operation> + + <wsdl:operation name="greetMeOneWay"> + <wsdl:input message="tns:greetMeOneWayRequest" name="greetMeOneWayRequest"/> + </wsdl:operation> + + <wsdl:operation name="greetMeWithCallback"> + <wsdl:input message="tns:greetMeRequest" name="greetMeRequest"/> + <wsdl:output message="tns:greetMeResponse" name="greetMeResponse"/> + </wsdl:operation> + + </wsdl:portType> + <wsdl:binding name="Greeter_SOAPBinding" type="tns:Greeter"> + <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + + <wsdl:operation name="sayHi"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="sayHiRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="sayHiResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + <wsdl:operation name="greetMe"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="greetMeResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + <wsdl:operation name="greetMeOneWay"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeOneWayRequest"> + <soap:body use="literal"/> + </wsdl:input> + </wsdl:operation> + + <wsdl:operation name="greetMeWithCallback"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="greetMeResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + </wsdl:binding> + <wsdl:service name="SOAPService"> + <wsdl:port binding="tns:Greeter_SOAPBinding" name="SoapPort"> + <soap:address location="http://localhost:9000/SoapContext/SoapPort"/> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/.checkstyle b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/.checkstyle new file mode 100644 index 0000000000..a2af63613f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/.checkstyle @@ -0,0 +1,24 @@ +<?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-M2/sca/services/bindings/binding.celtix/.pmd b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/.pmd new file mode 100644 index 0000000000..3e1ff77730 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/.pmd @@ -0,0 +1,23 @@ +<?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/> +</pmd> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/.ruleset new file mode 100644 index 0000000000..0933c1569c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/.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-M2/sca/services/bindings/binding.celtix/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/LICENSE.txt new file mode 100644 index 0000000000..0084319535 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, serviceDefinition 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-M2/sca/services/bindings/binding.celtix/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/README.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/README.txt new file mode 100644 index 0000000000..9b26d1690a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/README.txt @@ -0,0 +1,35 @@ +Apache Tuscany M1 build (May, 2006) +=================================== + +http://incubator.apache.org/tuscany/ + +Tuscany is an effort undergoing incubation at the Apache Software Foundation +(ASF), sponsored by the 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. + + +Support +------- + +Any problem with this release can be reported to the Tuscany mailing list +or in the JIRA issue tracker. + +Mailing list subscription: + tuscany-dev-subscribe@ws.apache.org + +Jira: + http://issues.apache.org/jira/browse/Tuscany + + +Thank you for using Tuscany! + + +The Tuscany Team. + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/pom.xml new file mode 100644 index 0000000000..0a71a1e338 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/pom.xml @@ -0,0 +1,96 @@ +<?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 xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <parent> + <groupId>org.apache.tuscany.sca.services.bindings</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>celtix</artifactId> + <name>Apache Tuscany Binding for Celtix</name> + <description>Implementation of the SCA Web Services binding using Celtix.</description> + + <properties> + <celtix.version>1.0</celtix.version> + <checkstyle.properties>checkstyle.severity=error</checkstyle.properties> + <sourcechecks.force>true</sourcechecks.force> + </properties> + <repositories> + <repository> + <id>objectweb</id> + <name>ObjectWeb repo</name> + <url>http://maven.objectweb.org/maven2</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>core</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>wsdl</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>databinding-sdo</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <!-- Celtix --> + <dependency> + <groupId>org.objectweb.celtix</groupId> + <artifactId>celtix-rt</artifactId> + <version>${celtix.version}</version> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymockclassextension</artifactId> + </dependency> + <dependency> + <groupId>woodstox</groupId> + <artifactId>wstx-asl</artifactId> + </dependency> + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/BusService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/BusService.java new file mode 100644 index 0000000000..238fbe97b0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/BusService.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.binding.celtix; + +import org.objectweb.celtix.Bus; + +/** + * A system service that returns the active Celtix <code>Bus</code> for the runtime + * + * @version $Rev$ $Date$ + */ +public interface BusService { + + /** + * Returns the active bus + */ + Bus getBus(); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/BusServiceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/BusServiceImpl.java new file mode 100644 index 0000000000..3a1c95c95e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/BusServiceImpl.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix; + +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistry; + +import org.objectweb.celtix.Bus; +import org.objectweb.celtix.BusException; +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Scope; + +/** + * The default implementation of the Celtix Bus system service + * + * @version $Rev$ $Date$ + */ +@Scope("MODULE") +public class BusServiceImpl implements BusService { + + protected WSDLDefinitionRegistry wsdlRegistry; + private Bus bus; + + public Bus getBus() { + return bus; + } + + /** + * FIXME the annotation processing framework must inject this + * @param wsdlReg + */ + @Property (override = "must") + public void setWsdlRegistry(WSDLDefinitionRegistry wsdlReg) { + wsdlRegistry = wsdlReg; + } + + /** + * Initializes the bus, set to be called when the runtime initializes the Celtix system composite + * @throws BusException + */ + @Init(eager = true) + public void init() throws BusException { + Map<String, Object> properties = new WeakHashMap<String, Object>(); + properties.put("celtix.WSDLManager", new TuscanyWSDLManager(wsdlRegistry)); + bus = Bus.init(new String[0], properties); + } + + /** + * Shuts down the bus, called when the runtime stops the Celtix system composite + * @throws BusException + */ + @Destroy + public void stop() throws BusException { + bus.shutdown(true); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixBindingBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixBindingBuilder.java new file mode 100644 index 0000000000..ec1a71b19d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixBindingBuilder.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix; + +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistry; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.BindingBuilderExtension; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.objectweb.celtix.Bus; + +import commonj.sdo.helper.TypeHelper; + +/** + * Builds a {@link org.apache.tuscany.spi.component.Service} or {@link org.apache.tuscany.spi.component.Reference} + * configured with the Celtix binding + * + * @version $Rev$ $Date$ + */ +public class CeltixBindingBuilder extends BindingBuilderExtension<WebServiceBinding> { + + private Bus bus; + + public Service build(CompositeComponent parent, + BoundServiceDefinition<WebServiceBinding> boundServiceDefinition, + DeploymentContext deploymentContext) { + WebServiceBinding wsBinding = boundServiceDefinition.getBinding(); + TypeHelper typeHelper = (TypeHelper) deploymentContext.getExtension(TypeHelper.class.getName()); + if (typeHelper == null) { + typeHelper = TypeHelper.INSTANCE; + } + if (bus == null) { + bus = getBus(wsBinding.getWSDLDefinitionRegistry()); + } + return new CeltixService( + boundServiceDefinition.getName(), + boundServiceDefinition.getServiceContract().getInterfaceClass(), + parent, + wireService, + wsBinding, + bus, + typeHelper); + } + + public Reference build(CompositeComponent parent, + BoundReferenceDefinition<WebServiceBinding> boundReferenceDefinition, + DeploymentContext deploymentContext) { + WebServiceBinding wsBinding = boundReferenceDefinition.getBinding(); + TypeHelper typeHelper = (TypeHelper) deploymentContext.getExtension(TypeHelper.class.getName()); + if (typeHelper == null) { + typeHelper = TypeHelper.INSTANCE; + } + if (bus == null) { + bus = getBus(wsBinding.getWSDLDefinitionRegistry()); + } + return new CeltixReference( + boundReferenceDefinition.getName(), + boundReferenceDefinition.getServiceContract().getInterfaceClass(), + parent, + wireService, + wsBinding, + bus, + typeHelper); + } + + protected Class<WebServiceBinding> getBindingType() { + return WebServiceBinding.class; + } + + private Bus getBus(WSDLDefinitionRegistry wsdlDefinitionRegistry) { + Bus celtixBus = null; + try { + Map<String, Object> properties = new WeakHashMap<String, Object>(); + properties.put("celtix.WSDLManager", new TuscanyWSDLManager(wsdlDefinitionRegistry)); + celtixBus = Bus.init(new String[0], properties); + } catch (Exception e) { + e.printStackTrace(); + } + return celtixBus; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixInvoker.java new file mode 100644 index 0000000000..aba5fd5984 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixInvoker.java @@ -0,0 +1,245 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix; + +import java.io.IOException; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; +import javax.jws.WebParam; +import javax.wsdl.Binding; +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.WSDLException; +import javax.wsdl.extensions.ExtensibilityElement; +import javax.wsdl.extensions.soap.SOAPAddress; +import javax.xml.namespace.QName; +import javax.xml.ws.Holder; + +import org.apache.tuscany.spi.builder.BuilderException; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import commonj.sdo.helper.TypeHelper; +import org.apache.tuscany.binding.celtix.io.SCADataBindingCallback; +import org.objectweb.celtix.Bus; +import org.objectweb.celtix.BusException; +import org.objectweb.celtix.bindings.ClientBinding; +import org.objectweb.celtix.bindings.DataBindingCallback; +import org.objectweb.celtix.bus.bindings.WSDLMetaDataCache; +import org.objectweb.celtix.bus.bindings.WSDLOperationInfo; +import org.objectweb.celtix.context.ObjectMessageContext; +import org.objectweb.celtix.ws.addressing.EndpointReferenceType; +import org.objectweb.celtix.wsdl.EndpointReferenceUtils; +import org.xmlsoap.schemas.wsdl.http.AddressType; + + +/** + * Responsible for dispatching a service operation invocation on a reference to the active Celtix <code>Bus</code> + * + * @version $Rev$ $Date$ + */ +public class CeltixInvoker implements TargetInvoker { + + private WSDLMetaDataCache wsdlCache; + + private ClientBinding clientBinding; + + private String operationName; + + private TypeHelper typeHelper; + + public CeltixInvoker(String operationName, + Bus bus, + Port port, + Service wsdlService, + Definition wsdlDef, + TypeHelper theTypeHelper) throws BuilderException { + this.wsdlCache = new WSDLMetaDataCache(wsdlDef, port); + this.operationName = operationName; + this.typeHelper = theTypeHelper; + // Definition wsdlDef = wsBinding.getWSDLDefinition(); + // wsdlCache = new WSDLMetaDataCache(wsdlDef, wsBinding.getWSDLPort()); + + try { + String key = wsdlDef.getDocumentBaseURI(); + URL url = new URL(key); + + QName qName = wsdlService.getQName(); + EndpointReferenceType reference = EndpointReferenceUtils.getEndpointReference(url, qName, port.getName()); + + String bindingId = null; + Binding binding = port.getBinding(); + if (null != binding) { + List list = binding.getExtensibilityElements(); + if (!list.isEmpty()) { + bindingId = ((ExtensibilityElement) list.get(0)).getElementType().getNamespaceURI(); + } + } + if (bindingId == null) { + List<?> list = port.getExtensibilityElements(); + for (Object ep : list) { + ExtensibilityElement ext = (ExtensibilityElement) ep; + if (ext instanceof SOAPAddress) { + bindingId = ((SOAPAddress) ext).getLocationURI(); + } + if (ext instanceof AddressType) { + bindingId = ((AddressType) ext).getLocation(); + } + } + + } + clientBinding = bus.getBindingManager().getBindingFactory(bindingId).createClientBinding(reference); + } catch (MalformedURLException e) { + throw new InvokerCreationException(e); + } catch (BusException e) { + throw new InvokerCreationException(e); + } catch (WSDLException e) { + throw new InvokerCreationException(e); + } catch (IOException e) { + throw new InvokerCreationException(e); + } + } + + /** + * Invoke an operation on the external Web service. + * + * @param args the Java object arguments to the WS operation + * @return the response from the WS as a Java object + */ + public Object invokeTarget(final Object args) throws InvocationTargetException { + WSDLOperationInfo opInfo = wsdlCache.getOperationInfo(operationName); + if (opInfo == null) { + // REVISIT - really map the operation name to a WSDL operation + for (String opName : wsdlCache.getAllOperationInfo().keySet()) { + if (operationName.equalsIgnoreCase(opName)) { + opInfo = wsdlCache.getOperationInfo(opName); + break; + } + } + } + + ObjectMessageContext objMsgContext = clientBinding.createObjectContext(); + + boolean hasInOut = false; + int inOutCount = 0; + Object realArgs[]; + Object argsArray[]; + if (args.getClass().isArray()) { + argsArray = (Object[]) args; + realArgs = new Object[Array.getLength(args)]; + } else { + argsArray = new Object[0]; + realArgs = new Object[0]; + } + + if (opInfo.getParamsLength() == 0) { + // REVISIT - opInfo doesn't return the needed info for the wrapped doc/lit case. + // Bug in Celtix + realArgs = argsArray; + } else { + for (int x = 0; x < argsArray.length; x++) { + if (opInfo.getWebParam(x).mode() == WebParam.Mode.IN) { + realArgs[x] = argsArray[x]; + } else { + realArgs[x] = new Holder<Object>(argsArray[x]); + inOutCount++; + hasInOut = true; + } + } + } + objMsgContext.setMessageObjects(realArgs); + boolean isOneway = opInfo.isOneWay(); + DataBindingCallback callback = new SCADataBindingCallback(opInfo, hasInOut, typeHelper); + try { + if (isOneway) { + clientBinding.invokeOneWay(objMsgContext, callback); + } else { + objMsgContext = clientBinding.invoke(objMsgContext, callback); + } + } catch (IOException e) { + throw new InvocationTargetException(e); + } + + if (objMsgContext.getException() != null) { + // REVISIT - Exceptions + /* + * if (isValidException(objMsgContext)) { throw + * (Exception)objMsgContext.getException(); } else { throw new + * ProtocolException(objMsgContext.getException()); } + */ + throw new InvocationTargetException(objMsgContext.getException()); + } + + if (hasInOut) { + Object ret[] = new Object[inOutCount + 1]; + ret[0] = objMsgContext.getReturn(); + inOutCount = 1; + for (int x = 0; x < argsArray.length; x++) { + if (opInfo.getWebParam(x).mode() != WebParam.Mode.IN) { + Holder<?> holder = (Holder<?>) realArgs[x]; + ret[inOutCount] = holder.value; + inOutCount++; + } + } + return ret; + } + return objMsgContext.getReturn(); + } + + public Message invoke(Message msg) { + try { + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } + + public void setNext(Interceptor next) { + throw new UnsupportedOperationException(); + } + + public CeltixInvoker clone() throws CloneNotSupportedException { + try { + return (CeltixInvoker) super.clone(); + } catch (CloneNotSupportedException e) { + // will not happen + return null; + } + } + + public boolean isCacheable() { + return true; + } + + public void setCacheable(boolean cacheable) { + + } + + public boolean isOptimizable() { + return false; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixReference.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixReference.java new file mode 100644 index 0000000000..c32f332d4b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixReference.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.binding.celtix; + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.extension.ReferenceExtension; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; + +import commonj.sdo.helper.TypeHelper; +import org.objectweb.celtix.Bus; + +/** + * The implementation of a {@link org.apache.tuscany.spi.component.Reference} configured with the Celtix binding + * + * @version $Rev$ $Date$ + */ +public class CeltixReference<T> extends ReferenceExtension { + + private Bus bus; + private Port port; + private Definition wsdlDef; + private Service wsdlService; + private TypeHelper typeHelper; + + public CeltixReference(String name, + Class<T> interfaze, + CompositeComponent parent, + WireService wireService, + WebServiceBinding binding, + Bus theBus, + TypeHelper theTypeHelper) { + super(name, interfaze, parent, wireService); + this.wsdlDef = binding.getWSDLDefinition(); + this.port = binding.getWSDLPort(); + this.wsdlService = binding.getWSDLService(); + this.bus = theBus; + this.typeHelper = theTypeHelper; + } + + public TargetInvoker createTargetInvoker(ServiceContract contract, Operation operation) { + return new CeltixInvoker(operation.getName(), bus, port, wsdlService, wsdlDef, typeHelper); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixService.java new file mode 100644 index 0000000000..097f0ac050 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixService.java @@ -0,0 +1,270 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix; + +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import javax.jws.soap.SOAPBinding; +import javax.wsdl.Binding; +import javax.wsdl.BindingInput; +import javax.wsdl.BindingOperation; +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.extensions.ExtensibilityElement; +import javax.wsdl.extensions.soap.SOAPAddress; +import javax.wsdl.extensions.soap.SOAPBody; +import javax.xml.namespace.QName; +import javax.xml.ws.WebServiceProvider; + +import org.osoa.sca.annotations.Destroy; + +import org.apache.tuscany.spi.CoreRuntimeException; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.wire.WireService; + +import commonj.sdo.helper.TypeHelper; +import org.apache.tuscany.binding.celtix.io.SCAServerDataBindingCallback; +import org.objectweb.celtix.Bus; +import org.objectweb.celtix.bindings.BindingFactory; +import org.objectweb.celtix.bindings.DataBindingCallback; +import org.objectweb.celtix.bindings.ServerBinding; +import org.objectweb.celtix.bindings.ServerBindingEndpointCallback; +import org.objectweb.celtix.bindings.ServerDataBindingCallback; +import org.objectweb.celtix.bus.bindings.WSDLMetaDataCache; +import org.objectweb.celtix.bus.bindings.WSDLOperationInfo; +import org.objectweb.celtix.context.ObjectMessageContext; +import org.objectweb.celtix.ws.addressing.AttributedURIType; +import org.objectweb.celtix.ws.addressing.EndpointReferenceType; +import org.objectweb.celtix.wsdl.EndpointReferenceUtils; +import org.xmlsoap.schemas.wsdl.http.AddressType; + + +/** + * An implementation of a {@link Service} configured with the Celtix binding + * + * @version $Rev$ $Date$ + */ +public class CeltixService extends ServiceExtension implements ServerBindingEndpointCallback { + + private Bus bus; + private Port port; + private Definition wsdlDef; + private Service wsdlService; + private WSDLMetaDataCache wsdlCache; + private TypeHelper typeHelper; + + private Map<QName, ServerDataBindingCallback> opMap = + new ConcurrentHashMap<QName, ServerDataBindingCallback>(); + + + public CeltixService(String theName, + Class<?> interfaze, + CompositeComponent parent, + WireService wireService, + WebServiceBinding binding, + Bus bus, + TypeHelper theTypeHelper) { + super(theName, interfaze, parent, wireService); + this.wsdlDef = binding.getWSDLDefinition(); + this.port = binding.getWSDLPort(); + this.wsdlService = binding.getWSDLService(); + this.bus = bus; + this.wsdlCache = new WSDLMetaDataCache(wsdlDef, port); + this.typeHelper = theTypeHelper; + } + + public void start() { + super.start(); + initOperationMap(); + startServerBinding(); + } + + private void startServerBinding() { + String key = wsdlDef.getDocumentBaseURI(); + URL url; + try { + url = new URL(key); + } catch (MalformedURLException e) { + throw new CeltixServiceInitException(e); + } + + QName qName = wsdlService.getQName(); + String portName = port.getName(); + EndpointReferenceType reference = EndpointReferenceUtils.getEndpointReference(url,qName,portName); + + AttributedURIType address = new AttributedURIType(); + + String bindingId = null; + Binding binding = port.getBinding(); + if (null != binding) { + List list = binding.getExtensibilityElements(); + if (!list.isEmpty()) { + bindingId = ((ExtensibilityElement) list.get(0)).getElementType().getNamespaceURI(); + } + } + List<?> list = port.getExtensibilityElements(); + for (Object ep : list) { + ExtensibilityElement ext = (ExtensibilityElement) ep; + if (ext instanceof SOAPAddress) { + if (bindingId == null) { + bindingId = ((SOAPAddress) ext).getLocationURI(); + } + address.setValue(((SOAPAddress) ext).getLocationURI()); + } + if (ext instanceof AddressType) { + if (bindingId == null) { + bindingId = ((AddressType) ext).getLocation(); + } + address.setValue(((AddressType) ext).getLocation()); + } + } + if (reference.getAddress() == null) { + //REVIST - bug in Celtix that the HTTP transport won't find the address correctly + reference.setAddress(address); + } + ClassLoader previousLoader = null; + try { + //FIXME: This hack is because SAAJImpl uses Thread.currentThread().getContextClassLoader(), + //this classloader is different from current classLoader. + previousLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + BindingFactory bindingFactory = bus.getBindingManager().getBindingFactory(bindingId); + ServerBinding serverBinding = bindingFactory.createServerBinding(reference, this); + serverBinding.activate(); + } catch (Exception e) { + throw new CeltixServiceInitException(e); + } finally { + if (previousLoader != null) { + Thread.currentThread().setContextClassLoader(previousLoader); + } + } + } + + private void initOperationMap() { + List ops = port.getBinding().getBindingOperations(); + for (Object op1 : ops) { + BindingOperation op = (BindingOperation) op1; + BindingInput bindingInput = op.getBindingInput(); + List elements = bindingInput.getExtensibilityElements(); + QName qn = new QName(wsdlDef.getTargetNamespace(), op.getName()); + + //In case soap:body namespace is different from targetNamespace + for (Object element : elements) { + if (SOAPBody.class.isInstance(element)) { + SOAPBody body = (SOAPBody) element; + if (body.getNamespaceURI() != null) { + qn = new QName(body.getNamespaceURI(), op.getName()); + } + } + } + + ServerDataBindingCallback cb = getDataBindingCallback(qn, null, DataBindingCallback.Mode.PARTS); + opMap.put(qn, cb); + if (!"".equals(cb.getRequestWrapperQName().getLocalPart())) { + opMap.put(cb.getRequestWrapperQName(), cb); + } + } + } + + @Destroy + public void stop() throws CoreRuntimeException { + super.stop(); + } + + public ServerDataBindingCallback getDataBindingCallback(QName operationName, + ObjectMessageContext objContext, + DataBindingCallback.Mode mode) { + if (opMap.containsKey(operationName)) { + return opMap.get(operationName); + } + WSDLOperationInfo opInfo = wsdlCache.getOperationInfo(operationName.getLocalPart()); + if (opInfo == null) { + //REVISIT - really map the operation name to a WSDL operation + for (String opName : wsdlCache.getAllOperationInfo().keySet()) { + if (operationName.getLocalPart().equalsIgnoreCase(opName)) { + opInfo = wsdlCache.getOperationInfo(opName); + break; + } + } + } + boolean inout = false; + + Class<?> serviceInterface = this.getInterface(); + Method meth = getMethod(serviceInterface, operationName.getLocalPart()); + + Object proxy = this.getServiceInstance(); + + return new SCAServerDataBindingCallback(opInfo, inout, meth, proxy, typeHelper); + } + + protected Method getMethod(Class<?> serviceInterface, String operationName) { + // Note: this doesn't support overloaded operations + Method[] methods = serviceInterface.getMethods(); + for (Method m : methods) { + if (m.getName().equals(operationName)) { + return m; + } + // tolerate WSDL with capatalized operation name + StringBuilder sb = new StringBuilder(operationName); + sb.setCharAt(0, Character.toLowerCase(sb.charAt(0))); + if (m.getName().equals(sb.toString())) { + return m; + } + } + throw new BuilderConfigException("no operation named " + operationName + + " found on service interface: " + serviceInterface.getName()); + } + + public DataBindingCallback getFaultDataBindingCallback(ObjectMessageContext objContext) { + // REVISIT - what to do about faults + return null; + } + + public Map<QName, ? extends DataBindingCallback> getOperations() { + return opMap; + } + + public SOAPBinding.Style getStyle() { + return wsdlCache.getStyle(); + } + + public DataBindingCallback.Mode getServiceMode() { + return DataBindingCallback.Mode.PARTS; + } + + public WebServiceProvider getWebServiceProvider() { + //not needed I think + return null; + } + + public Executor getExecutor() { + //Let the transport handle it (or it goes to the Bus default wq + //if the transport cannot handle it + return null; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixServiceInitException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixServiceInitException.java new file mode 100644 index 0000000000..4eca4a3bd1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/CeltixServiceInitException.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.binding.celtix; + +import org.apache.tuscany.spi.CoreRuntimeException; + +/** + * Denotes an exception starting a {@link CeltixService} instance + * + * @version $Rev$ $Date$ + */ +public class CeltixServiceInitException extends CoreRuntimeException { + public CeltixServiceInitException() { + } + + public CeltixServiceInitException(String message) { + super(message); + } + + public CeltixServiceInitException(String message, Throwable cause) { + super(message, cause); + } + + public CeltixServiceInitException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/InvokerCreationException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/InvokerCreationException.java new file mode 100644 index 0000000000..e08a3193d8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/InvokerCreationException.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.binding.celtix; + +import org.apache.tuscany.spi.builder.BuilderException; + +/** + * Thrown when an error is encountered creating a {@link CeltixInvoker} + * + * @version $Rev$ $Date$ + */ +public class InvokerCreationException extends BuilderException { + public InvokerCreationException() { + } + + public InvokerCreationException(String message) { + super(message); + } + + public InvokerCreationException(String message, Throwable cause) { + super(message, cause); + } + + public InvokerCreationException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/TuscanyWSDLManager.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/TuscanyWSDLManager.java new file mode 100644 index 0000000000..18efe80da5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/TuscanyWSDLManager.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix; + +import java.io.IOException; +import java.net.URL; +import javax.wsdl.Definition; +import javax.wsdl.WSDLException; +import javax.wsdl.extensions.ExtensionRegistry; +import javax.wsdl.factory.WSDLFactory; + +import org.w3c.dom.Element; +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistry; + +import org.objectweb.celtix.wsdl.WSDLManager; + +/** + * + * @version $Rev$ $Date$ + */ +public class TuscanyWSDLManager implements WSDLManager { + WSDLDefinitionRegistry wsdlDefinitionRegistry; + + public TuscanyWSDLManager(WSDLDefinitionRegistry w) { + wsdlDefinitionRegistry = w; + } + + public WSDLFactory getWSDLFactory() { + //Not supported + return null; + } + + public ExtensionRegistry getExtenstionRegistry() { + return wsdlDefinitionRegistry.getExtensionRegistry(); + } + + public Definition getDefinition(URL url) throws WSDLException { + try { + return wsdlDefinitionRegistry.loadDefinition(null, url); + } catch (IOException e) { + //FIXME + throw new WSDLException("", "", e); + } + } + + public Definition getDefinition(String url) throws WSDLException { + try { + //The namespace is the wsdl targetNamesapce, it is only used + //when the wsdl is created into cache. we are ok here to set it to null. + //FIXME pass the current ResourceLoader + return wsdlDefinitionRegistry.loadDefinition(null, new URL(url)); + } catch (IOException e) { + throw new WSDLException(WSDLException.CONFIGURATION_ERROR, e.getMessage()); + } + } + + public Definition getDefinition(Element el) throws WSDLException { + throw new UnsupportedOperationException(); + } + + public Definition getDefinition(Class<?> sei) throws WSDLException { + throw new UnsupportedOperationException(); + } + + public void addDefinition(Object key, Definition wsdl) { + throw new UnsupportedOperationException(); + } + + public void shutdown() { + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/WebServiceBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/WebServiceBinding.java new file mode 100644 index 0000000000..49df9a6e28 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/WebServiceBinding.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.binding.celtix; + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; + +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistry; +import org.apache.tuscany.spi.model.Binding; + +/** + * Represents a Celtix binding configuration in an assembly + * + * @version $Rev$ $Date$ + */ +public class WebServiceBinding extends Binding { + + private Definition definition; + private Port port; + private Service service; + //private String portURI; + private String uri; + //We have to use WebServiceBinding to pass WSDLDefinitionRegistry to BindingBuilder + private WSDLDefinitionRegistry wsdlDefinitionRegistry; + + public WebServiceBinding(Definition definition, Port port, String uri, String portURI, Service service) { + this.definition = definition; + this.port = port; + this.uri = uri; + //this.portURI = portURI; + this.service = service; + } + + public Port getWSDLPort() { + return port; + } + + public Service getWSDLService() { + return service; + } + + public void setWSDLPort(Port value) { + port = value; + } + + public Definition getWSDLDefinition() { + return definition; + } + + public void setWSDLDefinition(Definition def) { + definition = def; + } + + public WSDLDefinitionRegistry getWSDLDefinitionRegistry() { + return wsdlDefinitionRegistry; + } + + public void setWSDLDefinitionRegistry(WSDLDefinitionRegistry theWsdlDefinitionRegistry) { + wsdlDefinitionRegistry = theWsdlDefinitionRegistry; + } + +// public void setPortURI(String uri) { +// portURI = uri; +// } + + public String getURI() { + return uri; + } + + public void setURI(String theUri) { + this.uri = theUri; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/WebServiceBindingLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/WebServiceBindingLoader.java new file mode 100644 index 0000000000..5b11d02931 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/WebServiceBindingLoader.java @@ -0,0 +1,195 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix; + + +import java.io.IOException; +import java.net.URL; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.WSDLException; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.xml.sax.InputSource; +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; +import org.osoa.sca.annotations.Constructor; +import org.osoa.sca.annotations.Scope; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; + +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistry; +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistryImpl; +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistryImpl.Monitor; + +/** + * Parses a <code>WebServiceBinding</code> entry in an assembly XML file + * + * @version $Rev$ $Date$ + */ +@Scope("MODULE") +public class WebServiceBindingLoader extends LoaderExtension<WebServiceBinding> { + public static final QName BINDING_WS = new QName(XML_NAMESPACE_1_0, "binding.ws"); + + protected WSDLDefinitionRegistry wsdlRegistry; + + @Constructor({"registry"}) + public WebServiceBindingLoader(@Autowire LoaderRegistry registry) { + super(registry); + + //FIXME: this is a hack, WSDLDefinitionRegistry should not be created here + if (wsdlRegistry == null) { + try { + wsdlRegistry = new WSDLDefinitionRegistryImpl(); + Monitor monitor = new Monitor() { + public void readingWSDL(String namespace, URL location) { + } + + public void cachingDefinition(String namespace, URL location) { + } + }; + + ((WSDLDefinitionRegistryImpl) wsdlRegistry).setMonitor(monitor); + } catch (javax.wsdl.WSDLException e) { + //do nothing + } + } + } + + public QName getXMLType() { + return BINDING_WS; + } + + public WebServiceBinding load(CompositeComponent parent, + XMLStreamReader reader, + DeploymentContext deploymentContext) + throws XMLStreamException, LoaderException { + // not sure what uri was here ? String uri = reader.getAttributeValue(null, "uri"); + String uri = null; + String endpointAttribute = reader.getAttributeValue(null, "endpoint"); + //String portURI = reader.getAttributeValue(null, "port"); + String wsdlLocation = reader.getAttributeValue(null, "location"); + try { + return createBinding(uri, endpointAttribute, wsdlLocation, deploymentContext); + } catch (Exception e) { + + throw new LoaderException(e); + } + } + + private WebServiceBinding createBinding(String port, String portURI, String wsdlLocation, + DeploymentContext deploymentContext) + throws WSDLException, IOException { + List<Definition> definitions = null; + // FIXME wsdlRegistry.getDefinitionsForNamespace(portNamespace, + // resourceLoader); + // Get the WSDL port namespace and name + if (port == null && portURI != null) { + int h = portURI.indexOf('#'); + String portNamespace = portURI.substring(0, h); + String serviceName; + String portName; + + String fragment = portURI.substring(h + 1); + if (fragment.startsWith("wsdl.endpoint(") && fragment.endsWith(")")) { + fragment = fragment.substring(14, fragment.length() - 1); + int slash = fragment.indexOf('/'); + if (slash != -1) { + serviceName = fragment.substring(0, slash); + portName = fragment.substring(slash + 1); + } else { + serviceName = null; + portName = fragment; + } + } else { + serviceName = null; + portName = fragment; + } + + // FIXME need to find out how to get wsdl and what context to use --- terrible hack attack! + // URL wsdlurl = Thread.currentThread().getContextClassLoader().getResource(wsdlLocation); + if (null == wsdlLocation) { + throw new RuntimeException("Failed to determin wsdl location on binding. " + + "Try specifying 'location' attribute on binding."); + } + URL wsdlurl = deploymentContext.getClassLoader().getResource(wsdlLocation); + if (wsdlurl == null) { + throw new RuntimeException("Failed to load wsdl from '" + wsdlLocation + "'"); + } + + WSDLFactory factory = WSDLFactory.newInstance(); + WSDLReader reader = factory.newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + InputSource input = new InputSource(wsdlurl.openStream()); + Definition wsdlDef = reader.readWSDL(wsdlurl.toString(), input); + definitions = new LinkedList<Definition>(); + definitions.add(wsdlDef); + // FIXME all the above needs to better addressed. + + //FIXME: if a global wsdl cached is used, we need to do a registration here + String namespace = wsdlDef.getTargetNamespace(); + wsdlRegistry.loadDefinition(namespace, wsdlurl); + + Definition definition = null; + Port thePort = null; + Service service = null; + for (Definition def : definitions) { + + // Find the port with the given name + for (Service serv : (Collection<Service>) def.getServices().values()) { + QName sqn = serv.getQName(); + if (serviceName != null + && !serviceName.equals(sqn.getLocalPart())) { + continue; + } + + Port p = serv.getPort(portName); + if (p != null) { + service = serv; + definition = def; + thePort = p; + break; + } + } + } + if (thePort == null) { + throw new IllegalArgumentException("Cannot find WSDL port " + portURI); + + } + WebServiceBinding wsBinding = new WebServiceBinding(definition, thePort, port, portURI, service); + wsBinding.setWSDLDefinitionRegistry(wsdlRegistry); + return wsBinding; + } + // FIXME - return a broken binding for now + return new WebServiceBinding(null, null, null, portURI, null); + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/NodeDataReader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/NodeDataReader.java new file mode 100644 index 0000000000..7a14ab33fc --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/NodeDataReader.java @@ -0,0 +1,205 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.celtix.io; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.util.List; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import org.w3c.dom.Node; +import org.w3c.dom.bootstrap.DOMImplementationRegistry; +import static org.w3c.dom.bootstrap.DOMImplementationRegistry.PROPERTY; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSSerializer; + +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.model.DataType; + +import commonj.sdo.DataObject; +import commonj.sdo.Property; +import commonj.sdo.Type; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLDocument; + +import org.apache.tuscany.core.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.databinding.sdo.XMLStreamReader2XMLDocument; +import org.objectweb.celtix.bindings.DataReader; +import org.objectweb.celtix.context.ObjectMessageContext; + +public class NodeDataReader implements DataReader<Node> { + + private SCADataBindingCallback callback; + + public NodeDataReader(SCADataBindingCallback cb) { + callback = cb; + } + + public Object read(int idx, Node input) { + return read(null, idx, input); + } + + public Object read(QName name, int idx, Node input) { + try { + InputStream in = getNodeStream(input); + XMLInputFactory staxFactory = XMLInputFactory.newInstance(); + XMLStreamReader reader = staxFactory.createXMLStreamReader(in); + + XMLStreamReader2XMLDocument transformer = new XMLStreamReader2XMLDocument(); + TransformationContext context = new TransformationContextImpl(); + DataType<QName> binding = new DataType<QName>(DataObject.class, null); + binding.setMetadata(TypeHelper.class.getName(), callback.getTypeHelper()); + context.setTargetDataType(binding); + XMLDocument document = transformer.transform(reader, context); + + boolean isWrapped = false; + return toObjects(document, isWrapped); + } catch (Exception e) { + //REVISIT: better handling of exceptions + } + return null; + } + + public void readWrapper(ObjectMessageContext objCtx, boolean isOutBound, Node input) { + try { + QName wrapperName; + if (isOutBound) { + wrapperName = callback.getOperationInfo().getResponseWrapperQName(); + } else { + wrapperName = callback.getOperationInfo().getRequestWrapperQName(); + } + + Node nd = input.getFirstChild(); + while (nd != null + && !wrapperName.getNamespaceURI().equals(nd.getNamespaceURI()) + && !wrapperName.getLocalPart().equals(nd.getLocalName())) { + nd = nd.getNextSibling(); + } + + //REVISIT - This is SUCH a HACK. This needs to be done with StAX or something + //a bit better than streaming and reparsing + InputStream in = getNodeStream(nd); + XMLInputFactory staxFactory = XMLInputFactory.newInstance( + "javax.xml.stream.XMLInputFactory", getClass().getClassLoader()); + XMLStreamReader reader = staxFactory.createXMLStreamReader(in); + + XMLStreamReader2XMLDocument transformer = new XMLStreamReader2XMLDocument(); + TransformationContext context = new TransformationContextImpl(); + DataType<QName> binding = new DataType<QName>(DataObject.class, null); + binding.setMetadata(TypeHelper.class.getName(), callback.getTypeHelper()); + context.setTargetDataType(binding); + XMLDocument document = transformer.transform(reader, context); + + //boolean isWrapped = true; + Object[] objects = toObjects(document, true); + + if (callback.hasInOut()) { + //REVISIT - inOuts + } else { + if (isOutBound) { + objCtx.setReturn(objects[0]); + } else { + objCtx.setMessageObjects(objects); + } + } + } catch (Exception e) { + //REVISIT: better handling of exceptions + } + } + + /** + * Convert a typed DataObject to Java objects + * + * @param document + * @param isWrapped + * @return the array of Objects from the DataObject + */ + public static Object[] toObjects(XMLDocument document, boolean isWrapped) { + DataObject dataObject = document.getRootObject(); + if (isWrapped) { + List ips = dataObject.getInstanceProperties(); + Object[] os = new Object[ips.size()]; + for (int i = 0; i < ips.size(); i++) { + os[i] = dataObject.get((Property) ips.get(i)); + } + return os; + } else { + Object object = dataObject; + Type type = dataObject.getType(); + if (type.isSequenced()) { + object = dataObject.getSequence().getValue(0); + } + return new Object[]{object}; + } + } + + byte[] getNodeBytes(Node node) + throws ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException { + + //This is also a hack, the JDK should already have this set, but it doesn't + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + if (registry == null) { + System.setProperty(PROPERTY, "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl"); + registry = DOMImplementationRegistry.newInstance(); + } + DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + if (impl == null) { + System.setProperty(PROPERTY, "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl"); + registry = DOMImplementationRegistry.newInstance(); + impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + } + LSOutput output = impl.createLSOutput(); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + output.setByteStream(bout); + LSSerializer writer = impl.createLSSerializer(); + writer.write(node, output); + + return bout.toByteArray(); + } + + InputStream getNodeStream(Node node) + throws ClassCastException, ClassNotFoundException, + InstantiationException, IllegalAccessException { + + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + if (registry == null) { + //This is also a hack, the JDK should already have this set, but it doesn't + System.setProperty(PROPERTY, "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl"); + registry = DOMImplementationRegistry.newInstance(); + } + DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + if (impl == null) { + System.setProperty(PROPERTY, "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl"); + registry = DOMImplementationRegistry.newInstance(); + impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + } + LSOutput output = impl.createLSOutput(); + RawByteArrayOutputStream bout = new RawByteArrayOutputStream(); + output.setByteStream(bout); + LSSerializer writer = impl.createLSSerializer(); + writer.write(node, output); + + return new ByteArrayInputStream(bout.getBytes(), 0, bout.size()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/NodeDataWriter.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/NodeDataWriter.java new file mode 100644 index 0000000000..d870cafa87 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/NodeDataWriter.java @@ -0,0 +1,322 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.celtix.io; + +import java.util.List; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import org.apache.tuscany.spi.wire.InvocationRuntimeException; + +import commonj.sdo.DataObject; +import commonj.sdo.Property; +import commonj.sdo.Type; +import commonj.sdo.helper.DataFactory; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; +import commonj.sdo.helper.XSDHelper; +import org.apache.tuscany.databinding.sdo.XMLDocument2XMLStreamReader; +import org.apache.tuscany.sdo.util.SDOUtil; +import org.objectweb.celtix.bindings.DataWriter; +import org.objectweb.celtix.context.ObjectMessageContext; + +public class NodeDataWriter implements DataWriter<Node> { + private static final String XML_NS = "http://www.w3.org/2000/xmlns/"; + private SCADataBindingCallback callback; + + public NodeDataWriter(SCADataBindingCallback cb) { + callback = cb; + } + + public void write(Object obj, Node output) { + write(obj, null, output); + } + + public void write(Object obj, QName elName, Node output) { + boolean isWrapped = false; + + XMLDocument document = toXMLDocument(callback.getTypeHelper(), new Object[]{obj}, elName, isWrapped); + // HACK: [rfeng] We should use the transformer in an interceptor + XMLDocument2XMLStreamReader transformer = new XMLDocument2XMLStreamReader(); + XMLStreamReader reader = transformer.transform(document, null); + + try { + //CeltixFire supports Stax, we should not need to do following anymore. + readDocElements(output, reader, true, null); + } catch (XMLStreamException e) { + throw new InvocationRuntimeException(e.getMessage()); + } + } + + public void writeWrapper(ObjectMessageContext objCtx, boolean isOutbound, Node output) { + boolean isWrapped = true; + QName wrapperName; + if (isOutbound) { + wrapperName = callback.getOperationInfo().getResponseWrapperQName(); + } else { + wrapperName = callback.getOperationInfo().getRequestWrapperQName(); + } + + XMLDocument document = toXMLDocument( + callback.getTypeHelper(), objCtx.getMessageObjects(), wrapperName, isWrapped); + // HACK: [rfeng] We should use the transformer in an interceptor + XMLDocument2XMLStreamReader transformer = new XMLDocument2XMLStreamReader(); + XMLStreamReader reader = transformer.transform(document, null); + + try { + readDocElements(output, reader, true, null); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new InvocationRuntimeException(e.getMessage()); + } + } +/* + private DataObject toWrappedDataObject(TypeHelper typeHelper, + Object ret, + Object[] os, + QName typeQN) { + XSDHelper xsdHelper = new XSDHelperImpl(typeHelper); + Property property = xsdHelper.getGlobalProperty(typeQN.getNamespaceURI(), + typeQN.getLocalPart(), true); + DataObject dataObject = new DataFactoryImpl(typeHelper).create(property.getType()); + List ips = dataObject.getInstanceProperties(); + int offset = 0; + if (ret != null) { + dataObject.set(0, ret); + offset = 1; + } + for (int i = offset; i < ips.size(); i++) { + if (os[i - offset] instanceof Holder) { + Holder<?> holder = (Holder<?>)os[i - offset]; + dataObject.set(i, holder.value); + } else { + dataObject.set(i, os[i - offset]); + } + } + return dataObject; + } +*/ + + /** + * Convert objects to typed DataObject + * + * @param typeHelper + * @param os + * @param elementQName + * @param isWrapped + * @return the DataObject + */ + private static XMLDocument toXMLDocument(TypeHelper typeHelper, + Object[] os, + QName elementQName, + boolean isWrapped) { + XSDHelper xsdHelper = SDOUtil.createXSDHelper(typeHelper); + + Property property = xsdHelper.getGlobalProperty( + elementQName.getNamespaceURI(), elementQName.getLocalPart(), true); + if (null == property) { + throw new InvocationRuntimeException( + "Type '" + elementQName.toString() + "' not found in registered SDO types."); + } + DataObject dataObject; + if (isWrapped) { + DataFactory dataFactory = SDOUtil.createDataFactory(typeHelper); + dataObject = dataFactory.create(property.getType()); + List ips = dataObject.getInstanceProperties(); + for (int i = 0; i < ips.size(); i++) { + dataObject.set(i, os[i]); + } + } else { + Object value = os[0]; + Type type = property.getType(); + if (!type.isDataType()) { + dataObject = (DataObject) value; + } else { + dataObject = SDOUtil.createDataTypeWrapper(type, value); + } + } + + XMLHelper xmlHelper = SDOUtil.createXMLHelper(typeHelper); + return xmlHelper.createDocument(dataObject, elementQName.getNamespaceURI(), elementQName.getLocalPart()); + + } + + //REVISIT: We should not need to do following anymore with CeltixFire. + //As CeltixFire supports stax directly. + + /** + * @param parent + * @param reader + * @param repairing + * @param stopAt: stop at the specified element + * @throws XMLStreamException + */ + public static void readDocElements(Node parent, XMLStreamReader reader, boolean repairing, QName stopAt) + throws XMLStreamException { + Document doc = getDocument(parent); + + int event = reader.getEventType(); + + while (reader.hasNext()) { + switch (event) { + case XMLStreamConstants.START_ELEMENT: + if (startElement(parent, reader, repairing, stopAt) == null) { + return; + } + if (parent instanceof Document && stopAt != null) { + if (reader.hasNext()) { + reader.next(); + } + return; + } + break; + case XMLStreamConstants.END_ELEMENT: + return; + case XMLStreamConstants.NAMESPACE: + break; + case XMLStreamConstants.ATTRIBUTE: + break; + case XMLStreamConstants.CHARACTERS: + if (parent != null) { + parent.appendChild(doc.createTextNode(reader.getText())); + } + + break; + case XMLStreamConstants.COMMENT: + if (parent != null) { + parent.appendChild(doc.createComment(reader.getText())); + } + + break; + case XMLStreamConstants.CDATA: + parent.appendChild(doc.createCDATASection(reader.getText())); + + break; + case XMLStreamConstants.PROCESSING_INSTRUCTION: + parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData())); + + break; + case XMLStreamConstants.ENTITY_REFERENCE: + parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData())); + + break; + default: + break; + } + + if (reader.hasNext()) { + event = reader.next(); + } + } + } + + private static Document getDocument(Node parent) { + return (parent instanceof Document) ? (Document) parent : parent.getOwnerDocument(); + } + + /** + * @param parent + * @param reader + * @return + * @throws XMLStreamException + */ + private static Element startElement(Node parent, XMLStreamReader reader, boolean repairing, QName stopAt) + throws XMLStreamException { + Document doc = getDocument(parent); + + if (stopAt != null && stopAt.getNamespaceURI().equals(reader.getNamespaceURI()) + && stopAt.getLocalPart().equals(reader.getLocalName())) { + return null; + } + + Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName()); + + if (reader.getPrefix() != null) { + e.setPrefix(reader.getPrefix()); + } + + parent.appendChild(e); + + for (int ns = 0; ns < reader.getNamespaceCount(); ns++) { + String uri = reader.getNamespaceURI(ns); + String prefix = reader.getNamespacePrefix(ns); + + declare(e, uri, prefix); + } + + for (int att = 0; att < reader.getAttributeCount(); att++) { + String name = reader.getAttributeLocalName(att); + String prefix = reader.getAttributePrefix(att); + if (prefix != null && prefix.length() > 0) { + name = prefix + ":" + name; + } + + Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name); + attr.setValue(reader.getAttributeValue(att)); + e.setAttributeNode(attr); + } + + reader.next(); + + readDocElements(e, reader, repairing, stopAt); + + if (repairing && !isDeclared(e, reader.getNamespaceURI(), reader.getPrefix())) { + declare(e, reader.getNamespaceURI(), reader.getPrefix()); + } + + return e; + } + + private static void declare(Element node, String uri, String prefix) { + if (prefix != null && prefix.length() > 0) { + node.setAttributeNS(XML_NS, "xmlns:" + prefix, uri); + } else { + if (uri != null /* && uri.length() > 0 */) { + node.setAttributeNS(XML_NS, "xmlns", uri); + } + } + } + + private static boolean isDeclared(Element e, String namespaceURI, String prefix) { + Attr att; + if (prefix != null && prefix.length() > 0) { + att = e.getAttributeNodeNS(XML_NS, "xmlns:" + prefix); + } else { + att = e.getAttributeNode("xmlns"); + } + + if (att != null && att.getNodeValue().equals(namespaceURI)) { + return true; + } + + if (e.getParentNode() instanceof Element) { + return isDeclared((Element) e.getParentNode(), namespaceURI, prefix); + } + + return false; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/RawByteArrayOutputStream.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/RawByteArrayOutputStream.java new file mode 100644 index 0000000000..057481041b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/RawByteArrayOutputStream.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.celtix.io; + +import java.io.ByteArrayOutputStream; + +/** + * Just to allow raw access to the byte[] to avoid a copy + */ +class RawByteArrayOutputStream extends ByteArrayOutputStream { + public byte[] getBytes() { + return buf; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/SCADataBindingCallback.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/SCADataBindingCallback.java new file mode 100644 index 0000000000..47d130383f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/SCADataBindingCallback.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix.io; + +import org.w3c.dom.Node; + +import commonj.sdo.helper.TypeHelper; +import org.objectweb.celtix.bindings.DataReader; +import org.objectweb.celtix.bindings.DataWriter; +import org.objectweb.celtix.bus.bindings.AbstractWSDLOperationDataBindingCallback; +import org.objectweb.celtix.bus.bindings.WSDLOperationInfo; +import org.objectweb.celtix.context.ObjectMessageContext; + + +/** + * @version $Rev$ $Date$ + */ +public class SCADataBindingCallback extends AbstractWSDLOperationDataBindingCallback { + + protected boolean hasInOut; + protected TypeHelper typeHelper; + + public SCADataBindingCallback(WSDLOperationInfo op, boolean inout, TypeHelper theTypeHelper) { + super(op); + this.hasInOut = inout; + this.typeHelper = theTypeHelper; + } + + public boolean hasInOut() { + return hasInOut; + } + + public Mode getMode() { + return Mode.PARTS; + } + + public Class<?>[] getSupportedFormats() { + return new Class<?>[]{Node.class}; + } + + public TypeHelper getTypeHelper() { + return typeHelper; + } + + @SuppressWarnings("unchecked") + public <T> DataWriter<T> createWriter(Class<T> cls) { + if (cls == Node.class) { + return (DataWriter<T>) new NodeDataWriter(this); + } + return null; + } + + @SuppressWarnings("unchecked") + public <T> DataReader<T> createReader(Class<T> cls) { + if (cls == Node.class) { + return (DataReader<T>) new NodeDataReader(this); + } + //REVISIT - need to figure out what to do with Faults + return null; + } + + public void initObjectContext(ObjectMessageContext octx) { + //REVISIT - is this even used? + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/SCAServerDataBindingCallback.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/SCAServerDataBindingCallback.java new file mode 100644 index 0000000000..db9c624bd4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/java/org/apache/tuscany/binding/celtix/io/SCAServerDataBindingCallback.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.binding.celtix.io; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import commonj.sdo.helper.TypeHelper; + +import org.objectweb.celtix.bindings.ServerDataBindingCallback; +import org.objectweb.celtix.bus.bindings.WSDLOperationInfo; +import org.objectweb.celtix.context.ObjectMessageContext; + + +/** + * + * @version $Rev$ $Date$ + */ +public class SCAServerDataBindingCallback extends SCADataBindingCallback + implements ServerDataBindingCallback { + Method method; + Object targetObject; + + public SCAServerDataBindingCallback(WSDLOperationInfo op, + boolean inout, + Method meth, + Object target, + TypeHelper theTypeHelper) { + super(op, inout, theTypeHelper); + method = meth; + targetObject = target; + } + + + public void invoke(ObjectMessageContext octx) throws InvocationTargetException { + Object ret; + try { + ret = method.invoke(targetObject, octx.getMessageObjects()); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new InvocationTargetException(e); + } + octx.setReturn(ret); + } + + public void initObjectContext(ObjectMessageContext octx) { + Object o[] = new Object[method.getParameterTypes().length]; + //REVIST - holders? + octx.setMessageObjects(o); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..b6a5334903 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,31 @@ +<?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. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + name="org.apache.tuscany.binding.celtix.WebServiceBinding"> + + <component name="ws.implementationLoader"> + <system:implementation.system class="org.apache.tuscany.binding.celtix.WebServiceBindingLoader" /> + </component> + + <component name="ws.componentBuilder"> + <system:implementation.system class="org.apache.tuscany.binding.celtix.CeltixBindingBuilder" /> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/BootstrapTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/BootstrapTestCase.java new file mode 100644 index 0000000000..cba83a7792 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/BootstrapTestCase.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.binding.celtix; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class BootstrapTestCase extends TestCase { + + public void testReference() throws Exception { +// BusServiceImpl busService = new BusServiceImpl(); +// WSDLDefinitionRegistry wsdlRegistry = new WSDLDefinitionRegistryImpl(); +// busService.setWsdlRegistry(wsdlRegistry); +// busService.init(); +// CeltixReference reference = new CeltixReference("reference",); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/CeltixInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/CeltixInvokerTestCase.java new file mode 100644 index 0000000000..5440fc22ce --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/CeltixInvokerTestCase.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.binding.celtix; + +import java.net.URL; +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +import org.xml.sax.InputSource; + +import junit.framework.TestCase; +import org.apache.tuscany.binding.celtix.io.SCADataBindingCallback; +import org.easymock.classextension.EasyMock; +import org.objectweb.celtix.Bus; +import org.objectweb.celtix.bindings.BindingManager; +import org.objectweb.celtix.bus.bindings.soap.SOAPBindingFactory; +import org.objectweb.celtix.bus.bindings.soap.SOAPClientBinding; +import org.objectweb.celtix.context.ObjectMessageContextImpl; +import org.objectweb.celtix.ws.addressing.EndpointReferenceType; + +/** + * @version $Rev$ $Date$ + */ +public class CeltixInvokerTestCase extends TestCase { + + public void testProcessingInputWithoutInOut() throws Exception { + String wsdlLocation = "/wsdl/hello_world_doc_lit.wsdl"; + String operationName = "greetMe"; + ObjectMessageContextImpl inputCtx = new ObjectMessageContextImpl(); + CeltixInvoker invoker = createCeltixInvoker(wsdlLocation, + operationName, inputCtx); + + Object[] args = new Object[1]; + args[0] = new String("hello"); + invoker.invokeTarget(args); + + // Check the input object after processing is correct + // Should be no change for input if only IN parameters involved + Object[] myrtn = (Object[]) inputCtx.getMessageObjects(); + + assertEquals("hello", myrtn[0]); + } + + public void testProcessingInputWithInOut() throws Exception { + String wsdlLocation = "/wsdl/hello_world_doc_lit_inout.wsdl"; + String operationName = "greetMe"; + ObjectMessageContextImpl inputCtx = new ObjectMessageContextImpl(); + CeltixInvoker invoker = createCeltixInvoker(wsdlLocation, + operationName, inputCtx); + + Object[] args = new Object[1]; + String inputvalue = new String("hello"); + args[0] = inputvalue; + Object result = invoker.invokeTarget(args); + + // Check the input object after processing is correct + // input should be wrapped as Holder type if it is INOUT parameter + Object[] myrtn = (Object[]) inputCtx.getMessageObjects(); + + //FIXME: this does not work for the wrapped doc/lit case due to a bug in Celtix + //assertTrue("input is not Holder type", myrtn[0] instanceof Holder); + } + + // NOTE: For convenience this method presumes the soap service name is + // SOAPService and port name is SoapPort + private CeltixInvoker createCeltixInvoker(String wsdlLocation, + String operationName, + ObjectMessageContextImpl inputCtx) + throws Exception { + + // Make following call to return a mocked SOAPClientBinding: + // bus.getBindingManager().getBindingFactory(bindingId).createClientBinding(reference) + SOAPClientBinding clientBinding = EasyMock + .createMock(SOAPClientBinding.class); + clientBinding.createObjectContext(); + EasyMock.expectLastCall().andReturn(inputCtx); + clientBinding.invoke(EasyMock.isA(ObjectMessageContextImpl.class), + EasyMock.isA(SCADataBindingCallback.class)); + EasyMock.expectLastCall().andReturn(new ObjectMessageContextImpl()); + EasyMock.replay(clientBinding); + + SOAPBindingFactory bindingFactory = EasyMock.createNiceMock(SOAPBindingFactory.class); + bindingFactory.createClientBinding(EasyMock.isA(EndpointReferenceType.class)); + EasyMock.expectLastCall().andReturn(clientBinding); + EasyMock.replay(bindingFactory); + + BindingManager bindingManager = EasyMock.createNiceMock(BindingManager.class); + String bindingId = "http://schemas.xmlsoap.org/wsdl/soap/"; + bindingManager.getBindingFactory(bindingId); + EasyMock.expectLastCall().andReturn(bindingFactory); + + Bus bus = EasyMock.createNiceMock(Bus.class); + bus.getBindingManager(); + EasyMock.expectLastCall().andReturn(bindingManager); + EasyMock.replay(bindingManager); + EasyMock.replay(bus); + + // Create WSDL Definition + URL url = getClass().getResource(wsdlLocation); + assertNotNull("Could not find wsdl " + url.toString(), url); + + WSDLFactory factory = WSDLFactory.newInstance(); + WSDLReader reader = factory.newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + InputSource input = new InputSource(url.openStream()); + Definition wsdlDef = reader.readWSDL(url.toString(), input); + QName qName = new QName("http://objectweb.org/hello_world_soap_http", "SOAPService"); + Service wsdlService = wsdlDef.getService(qName); + Port port = wsdlService.getPort("SoapPort"); + + return new CeltixInvoker(operationName, bus, port, wsdlService, wsdlDef, null); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/CeltixServiceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/CeltixServiceTestCase.java new file mode 100644 index 0000000000..1a66aa4eb5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/CeltixServiceTestCase.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.binding.celtix; + +import java.net.URL; +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +import org.xml.sax.InputSource; + +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.easymock.classextension.EasyMock; +import org.objectweb.celtix.Bus; +import org.objectweb.celtix.bindings.BindingManager; +import static org.objectweb.celtix.bindings.DataBindingCallback.Mode.PARTS; +import org.objectweb.celtix.bindings.ServerBindingEndpointCallback; +import org.objectweb.celtix.bindings.ServerDataBindingCallback; +import org.objectweb.celtix.bus.bindings.soap.SOAPBindingFactory; +import org.objectweb.celtix.bus.bindings.soap.SOAPServerBinding; +import org.objectweb.celtix.context.ObjectMessageContextImpl; +import org.objectweb.celtix.ws.addressing.EndpointReferenceType; + +/** + * @version $Rev$ $Date$ + */ +public class CeltixServiceTestCase extends TestCase { + + public void testGetDataBindingCallback() throws Exception { + CeltixService celtixService = createCeltixService(); + + QName operationName = new QName("greetMe"); + ObjectMessageContextImpl ctx = new ObjectMessageContextImpl(); + ctx.setMessageObjects(new String[]{"Celtix"}); + ServerDataBindingCallback callback1 = celtixService.getDataBindingCallback(operationName, ctx, PARTS); + assertNotNull(callback1); + + callback1.invoke(ctx); + Object rtn = (String) ctx.getReturn(); + assertEquals("Hello Celtix", rtn); + + } + + private CeltixService createCeltixService() throws Exception { + //Make following call to return a mocked SOAPClientBinding: + //bus.getBindingManager().getBindingFactory(bindingId).createClientBinding(reference) + SOAPServerBinding serverBinding = EasyMock.createMock(SOAPServerBinding.class); + serverBinding.activate(); + EasyMock.replay(serverBinding); + + //ServerBindingEndpointCallback callback = EasyMock.createNiceMock(ServerBindingEndpointCallback.class); + + SOAPBindingFactory bindingFactory = EasyMock.createNiceMock(SOAPBindingFactory.class); + bindingFactory.createServerBinding(EasyMock.isA(EndpointReferenceType.class), + EasyMock.isA(ServerBindingEndpointCallback.class)); + EasyMock.expectLastCall().andReturn(serverBinding); + EasyMock.replay(bindingFactory); + + BindingManager bindingManager = EasyMock.createNiceMock(BindingManager.class); + String bindingId = "http://schemas.xmlsoap.org/wsdl/soap/"; + bindingManager.getBindingFactory(bindingId); + EasyMock.expectLastCall().andReturn(bindingFactory); + + Bus bus = EasyMock.createNiceMock(Bus.class); + bus.getBindingManager(); + EasyMock.expectLastCall().andReturn(bindingManager); + EasyMock.replay(bindingManager); + EasyMock.replay(bus); + + //Create WSDL Definition + String wsdlLocation = "/wsdl/hello_world_doc_lit.wsdl"; + URL url = getClass().getResource(wsdlLocation); + assertNotNull("Could not find wsdl " + url.toString(), url); + + WSDLFactory factory = WSDLFactory.newInstance(); + WSDLReader reader = factory.newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + InputSource input = new InputSource(url.openStream()); + Definition wsdlDef = reader.readWSDL(url.toString(), input); + Service wsdlService = wsdlDef.getService(new QName("http://objectweb.org/hello_world_soap_http", + "SOAPService")); + Port port = wsdlService.getPort("SoapPort"); + + WebServiceBinding wsBinding = new WebServiceBinding(wsdlDef, port, "uri", "portURI", wsdlService); + + //Create mocked InboundWire, for ServiceExtension.getInterface() + InboundWire inboundWire = EasyMock.createNiceMock(InboundWire.class); + JavaServiceContract contract = new JavaServiceContract(Greeter.class); + EasyMock.expect(inboundWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.replay(inboundWire); + + //Create mocked WireService, for ServiceExtension.getServiceInstance() + WireService wireService = EasyMock.createNiceMock(WireService.class); + wireService.createProxy(EasyMock.isA(InboundWire.class)); + EasyMock.expectLastCall().andReturn(new GreeterImpl()).anyTimes(); + EasyMock.replay(wireService); + + CeltixService celtixService = new CeltixService("name", Greeter.class, null, wireService, wsBinding, bus, null); + //Not sure how InboundWire is set to CeltixService, is the following way correct? + celtixService.setInboundWire(inboundWire); + celtixService.start(); + + return celtixService; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/Greeter.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/Greeter.java new file mode 100644 index 0000000000..56de472774 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/Greeter.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix; + +public interface Greeter { + java.lang.String sayHi(); + + java.lang.String greetMe( + java.lang.String requestType + ); + + void greetMeOneWay( + java.lang.String requestType + ); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/GreeterImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/GreeterImpl.java new file mode 100644 index 0000000000..38237ad81a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/java/org/apache/tuscany/binding/celtix/GreeterImpl.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.celtix; + +public class GreeterImpl implements Greeter { + public java.lang.String sayHi() { + return "sayHi"; + } + + public java.lang.String greetMe(String requestType) { + return "Hello " + requestType; + } + + public void greetMeOneWay(String requestType) { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world.wsdl new file mode 100644 index 0000000000..e8767988f3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world.wsdl @@ -0,0 +1,181 @@ +<?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. +--> +<wsdl:definitions name="HelloWorld" targetNamespace="http://objectweb.org/hello_world_soap_http" + xmlns="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:tns="http://objectweb.org/hello_world_soap_http" + xmlns:x1="http://objectweb.org/hello_world_soap_http/types" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <wsdl:types> + <schema targetNamespace="http://objectweb.org/hello_world_soap_http/types" + xmlns="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://objectweb.org/hello_world_soap_http/types" + elementFormDefault="qualified"> + <simpleType name="MyStringType"> + <restriction base="string"> + <maxLength value="30" /> + </restriction> + </simpleType> + + <element name="sayHi"> + <complexType/> + </element> + <element name="sayHiResponse"> + <complexType> + <sequence> + <element name="responseType" type="string"/> + </sequence> + </complexType> + </element> + <element name="greetMe"> + <complexType> + <sequence> + <element name="requestType" type="tns:MyStringType"/> + </sequence> + </complexType> + </element> + <element name="greetMeResponse"> + <complexType> + <sequence> + <element name="responseType" type="string"/> + </sequence> + </complexType> + </element> + <element name="greetMeOneWay"> + <complexType> + <sequence> + <element name="requestType" type="string"/> + </sequence> + </complexType> + </element> + <element name="pingMe"> + <complexType/> + </element> + <element name="pingMeResponse"> + <complexType/> + </element> + <element name="faultDetail"> + <complexType> + <sequence> + <element name="minor" type="short"/> + <element name="major" type="short"/> + </sequence> + </complexType> + </element> + </schema> + </wsdl:types> + <wsdl:message name="sayHiRequest"> + <wsdl:part element="x1:sayHi" name="in"/> + </wsdl:message> + <wsdl:message name="sayHiResponse"> + <wsdl:part element="x1:sayHiResponse" name="out"/> + </wsdl:message> + <wsdl:message name="greetMeRequest"> + <wsdl:part element="x1:greetMe" name="in"/> + </wsdl:message> + <wsdl:message name="greetMeResponse"> + <wsdl:part element="x1:greetMeResponse" name="out"/> + </wsdl:message> + <wsdl:message name="greetMeOneWayRequest"> + <wsdl:part element="x1:greetMeOneWay" name="in"/> + </wsdl:message> + <wsdl:message name="pingMeRequest"> + <wsdl:part name="in" element="x1:pingMe"/> + </wsdl:message> + <wsdl:message name="pingMeResponse"> + <wsdl:part name="out" element="x1:pingMeResponse"/> + </wsdl:message> + <wsdl:message name="pingMeFault"> + <wsdl:part name="faultDetail" element="x1:faultDetail"/> + </wsdl:message> + + <wsdl:portType name="Greeter"> + <wsdl:operation name="sayHi"> + <wsdl:input message="tns:sayHiRequest" name="sayHiRequest"/> + <wsdl:output message="tns:sayHiResponse" name="sayHiResponse"/> + </wsdl:operation> + + <wsdl:operation name="greetMe"> + <wsdl:input message="tns:greetMeRequest" name="greetMeRequest"/> + <wsdl:output message="tns:greetMeResponse" name="greetMeResponse"/> + </wsdl:operation> + + <wsdl:operation name="greetMeOneWay"> + <wsdl:input message="tns:greetMeOneWayRequest" name="greetMeOneWayRequest"/> + </wsdl:operation> + + <wsdl:operation name="pingMe"> + <wsdl:input name="pingMeRequest" message="tns:pingMeRequest"/> + <wsdl:output name="pingMeResponse" message="tns:pingMeResponse"/> + <wsdl:fault name="pingMeFault" message="tns:pingMeFault"/> + </wsdl:operation> + </wsdl:portType> + <wsdl:binding name="Greeter_SOAPBinding" type="tns:Greeter"> + <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + + <wsdl:operation name="sayHi"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="sayHiRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="sayHiResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + <wsdl:operation name="greetMe"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="greetMeResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + <wsdl:operation name="greetMeOneWay"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeOneWayRequest"> + <soap:body use="literal"/> + </wsdl:input> + </wsdl:operation> + + <wsdl:operation name="pingMe"> + <soap:operation style="document"/> + <wsdl:input> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output> + <soap:body use="literal"/> + </wsdl:output> + <wsdl:fault name="pingMeFault"> + <soap:fault name="pingMeFault" use="literal"/> + </wsdl:fault> + </wsdl:operation> + + </wsdl:binding> + <wsdl:serviceDefinition name="SOAPService"> + <wsdl:port binding="tns:Greeter_SOAPBinding" name="SoapPort"> + <soap:address location="http://localhost:9000/SoapContext/SoapPort"/> + </wsdl:port> + </wsdl:serviceDefinition> +</wsdl:definitions> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world_doc_lit.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world_doc_lit.wsdl new file mode 100644 index 0000000000..db625cb129 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world_doc_lit.wsdl @@ -0,0 +1,154 @@ +<?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. +--> +<wsdl:definitions name="HelloWorld" targetNamespace="http://objectweb.org/hello_world_soap_http" + xmlns="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:tns="http://objectweb.org/hello_world_soap_http" + xmlns:x1="http://objectweb.org/hello_world_soap_http/types" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <wsdl:types> + <schema targetNamespace="http://objectweb.org/hello_world_soap_http/types" + xmlns="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://objectweb.org/hello_world_soap_http/types" + elementFormDefault="qualified"> + <simpleType name="MyStringType"> + <restriction base="string"> + <maxLength value="30" /> + </restriction> + </simpleType> + + <element name="sayHi"> + <complexType/> + </element> + <element name="sayHiResponse"> + <complexType> + <sequence> + <element name="responseType" type="string"/> + </sequence> + </complexType> + </element> + <element name="greetMe"> + <complexType> + <sequence> + <element name="requestType" type="tns:MyStringType"/> + </sequence> + </complexType> + </element> + <element name="greetMeResponse"> + <complexType> + <sequence> + <element name="responseType" type="string"/> + </sequence> + </complexType> + </element> + <element name="greetMeOneWay"> + <complexType> + <sequence> + <element name="requestType" type="string"/> + </sequence> + </complexType> + </element> + <element name="pingMe"> + <complexType/> + </element> + <element name="pingMeResponse"> + <complexType/> + </element> + <element name="faultDetail"> + <complexType> + <sequence> + <element name="minor" type="short"/> + <element name="major" type="short"/> + </sequence> + </complexType> + </element> + </schema> + </wsdl:types> + <wsdl:message name="sayHiRequest"> + <wsdl:part element="x1:sayHi" name="in"/> + </wsdl:message> + <wsdl:message name="sayHiResponse"> + <wsdl:part element="x1:sayHiResponse" name="out"/> + </wsdl:message> + <wsdl:message name="greetMeRequest"> + <wsdl:part element="x1:greetMe" name="in"/> + </wsdl:message> + <wsdl:message name="greetMeResponse"> + <wsdl:part element="x1:greetMeResponse" name="out"/> + </wsdl:message> + <wsdl:message name="greetMeOneWayRequest"> + <wsdl:part element="x1:greetMeOneWay" name="in"/> + </wsdl:message> + + <wsdl:portType name="Greeter"> + <wsdl:operation name="sayHi"> + <wsdl:input message="tns:sayHiRequest" name="sayHiRequest"/> + <wsdl:output message="tns:sayHiResponse" name="sayHiResponse"/> + </wsdl:operation> + + <wsdl:operation name="greetMe"> + <wsdl:input message="tns:greetMeRequest" name="greetMeRequest"/> + <wsdl:output message="tns:greetMeResponse" name="greetMeResponse"/> + </wsdl:operation> + + <wsdl:operation name="greetMeOneWay"> + <wsdl:input message="tns:greetMeOneWayRequest" name="greetMeOneWayRequest"/> + </wsdl:operation> + + </wsdl:portType> + <wsdl:binding name="Greeter_SOAPBinding" type="tns:Greeter"> + <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + + <wsdl:operation name="sayHi"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="sayHiRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="sayHiResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + <wsdl:operation name="greetMe"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="greetMeResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + <wsdl:operation name="greetMeOneWay"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeOneWayRequest"> + <soap:body use="literal"/> + </wsdl:input> + </wsdl:operation> + + </wsdl:binding> + <wsdl:service name="SOAPService"> + <wsdl:port binding="tns:Greeter_SOAPBinding" name="SoapPort"> + <soap:address location="http://localhost:9000/SoapContext/SoapPort"/> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world_doc_lit_inout.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world_doc_lit_inout.wsdl new file mode 100644 index 0000000000..90634709ba --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/src/test/resources/wsdl/hello_world_doc_lit_inout.wsdl @@ -0,0 +1,181 @@ +<?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. +--> +<wsdl:definitions name="HelloWorld" targetNamespace="http://objectweb.org/hello_world_soap_http" + xmlns="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:tns="http://objectweb.org/hello_world_soap_http" + xmlns:x1="http://objectweb.org/hello_world_soap_http/types" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <wsdl:types> + <schema targetNamespace="http://objectweb.org/hello_world_soap_http/types" + xmlns="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://objectweb.org/hello_world_soap_http/types" + elementFormDefault="qualified"> + <simpleType name="MyStringType"> + <restriction base="string"> + <maxLength value="30" /> + </restriction> + </simpleType> + + <element name="sayHi"> + <complexType/> + </element> + <element name="sayHiResponse"> + <complexType> + <sequence> + <element name="responseType" type="string"/> + </sequence> + </complexType> + </element> + <element name="greetMe"> + <complexType> + <sequence> + <element name="requestType" type="tns:MyStringType"/> + </sequence> + </complexType> + </element> + <element name="greetMeResponse"> + <complexType> + <sequence> + <element name="responseType" type="string"/> + </sequence> + </complexType> + </element> + <element name="greetMeOneWay"> + <complexType> + <sequence> + <element name="requestType" type="string"/> + </sequence> + </complexType> + </element> + <element name="pingMe"> + <complexType/> + </element> + <element name="pingMeResponse"> + <complexType/> + </element> + <element name="faultDetail"> + <complexType> + <sequence> + <element name="minor" type="short"/> + <element name="major" type="short"/> + </sequence> + </complexType> + </element> + </schema> + </wsdl:types> + <wsdl:message name="sayHiRequest"> + <wsdl:part element="x1:sayHi" name="in"/> + </wsdl:message> + <wsdl:message name="sayHiResponse"> + <wsdl:part element="x1:sayHiResponse" name="out"/> + </wsdl:message> + <wsdl:message name="greetMeRequest"> + <wsdl:part element="x1:greetMe" name="in"/> + </wsdl:message> + <wsdl:message name="greetMeResponse"> + <wsdl:part element="x1:greetMe" name="out"/> + </wsdl:message> + <wsdl:message name="greetMeOneWayRequest"> + <wsdl:part element="x1:greetMeOneWay" name="in"/> + </wsdl:message> + <wsdl:message name="pingMeRequest"> + <wsdl:part name="in" element="x1:pingMe"/> + </wsdl:message> + <wsdl:message name="pingMeResponse"> + <wsdl:part name="out" element="x1:pingMeResponse"/> + </wsdl:message> + <wsdl:message name="pingMeFault"> + <wsdl:part name="faultDetail" element="x1:faultDetail"/> + </wsdl:message> + + <wsdl:portType name="Greeter"> + <wsdl:operation name="sayHi"> + <wsdl:input message="tns:sayHiRequest" name="sayHiRequest"/> + <wsdl:output message="tns:sayHiResponse" name="sayHiResponse"/> + </wsdl:operation> + + <wsdl:operation name="greetMe"> + <wsdl:input message="tns:greetMeRequest" name="greetMeRequest"/> + <wsdl:output message="tns:greetMeResponse" name="greetMeResponse"/> + </wsdl:operation> + + <wsdl:operation name="greetMeOneWay"> + <wsdl:input message="tns:greetMeOneWayRequest" name="greetMeOneWayRequest"/> + </wsdl:operation> + + <wsdl:operation name="pingMe"> + <wsdl:input name="pingMeRequest" message="tns:pingMeRequest"/> + <wsdl:output name="pingMeResponse" message="tns:pingMeResponse"/> + <wsdl:fault name="pingMeFault" message="tns:pingMeFault"/> + </wsdl:operation> + </wsdl:portType> + <wsdl:binding name="Greeter_SOAPBinding" type="tns:Greeter"> + <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + + <wsdl:operation name="sayHi"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="sayHiRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="sayHiResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + <wsdl:operation name="greetMe"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeRequest"> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output name="greetMeResponse"> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + + <wsdl:operation name="greetMeOneWay"> + <soap:operation soapAction="" style="document"/> + <wsdl:input name="greetMeOneWayRequest"> + <soap:body use="literal"/> + </wsdl:input> + </wsdl:operation> + + <wsdl:operation name="pingMe"> + <soap:operation style="document"/> + <wsdl:input> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output> + <soap:body use="literal"/> + </wsdl:output> + <wsdl:fault name="pingMeFault"> + <soap:fault name="pingMeFault" use="literal"/> + </wsdl:fault> + </wsdl:operation> + + </wsdl:binding> + <wsdl:service name="SOAPService"> + <wsdl:port binding="tns:Greeter_SOAPBinding" name="SoapPort"> + <soap:address location="http://localhost:9000/SoapContext/SoapPort"/> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/tuscany-checkstyle.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/tuscany-checkstyle.xml new file mode 100644 index 0000000000..df8a9483d5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.celtix/tuscany-checkstyle.xml @@ -0,0 +1,288 @@ +<?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. +--> +<!DOCTYPE module PUBLIC + "-//Puppy Crawl//DTD Check Configuration 1.2//EN" + "http://www.puppycrawl.com/dtds/configuration_1_2.dtd"> + +<!-- +Checks to make sure the code meets the Tuscany coding guidelines +http://java.sun.com/docs/codeconv/index.html + +It also enforces aa bunch of other "BestPractices like method +lengths, if/try depths, etc... + +--> + +<module name="Checker"> + <property name="severity" + value="${checkstyle.severity}" + default="warning"/> + + <!-- Checks whether files end with a new line. --> + <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile --> + <!-- + <module name="NewlineAtEndOfFile"/> + --> + + <!-- Checks that property files contain the same keys. --> + <!-- See http://checkstyle.sf.net/config_misc.html#Translation --> + <module name="Translation"/> + + <!--<module name="StrictDuplicateCode"/>--> + + <module name="TreeWalker"> + + <!-- Checks for Javadoc comments. --> + <!-- See http://checkstyle.sf.net/config_javadoc.html --> + <!-- + <module name="PackageHtml"/> + <module name="JavadocMethod"/> + <module name="JavadocType"/> + <module name="JavadocVariable"/> + <module name="JavadocStyle"/> + --> + + + <!-- Checks for Naming Conventions. --> + <!-- See http://checkstyle.sf.net/config_naming.html --> + <module name="AbstractClassName"> + <property name="format" + value="^Abstract.*$|^.*Factory$|^.*Bus$|^.*ConfigurationRepository$|^.*Base$|^Exception$|^.*Builder$"/> + </module> + <module name="ConstantName"/> + <module name="LocalFinalVariableName"/> + <module name="LocalVariableName"/> + <module name="MemberName"/> + <module name="MethodName"/> + <module name="PackageName"/> + <module name="ParameterName"/> + <module name="StaticVariableName"/> + <module name="TypeName"/> + + <!-- Header checks --> + <!-- <module name="Header"/> --> + <!-- <module name="RegexpHeader"/> --> + + + <!-- Checks for imports --> + <!-- See http://checkstyle.sf.net/config_import.html --> + <module name="AvoidStarImport"> + <property name="excludes" + value="java.io,java.util,java.net,java.nio,java.nio.channels,java.lang.reflect,org.w3c.dom,org.xml.sax,java.awt,javax.swing,junit.framework"/> + </module> + <module name="IllegalImport"/> + <!-- defaults to sun.* packages --> + <module name="RedundantImport"/> + <module name="UnusedImports"/> + <module name="ImportOrder"> + <property name="groups" value="java,javax,org.w3c,org.xml,w3c"/> + <property name="ordered" value="true"/> + </module> + <!-- + <module name="ImportControl"> + <property name="file" value="etc/import-control.xml"/> + </module> + --> + + + <!-- Checks for Size Violations. --> + <!-- See http://checkstyle.sf.net/config_sizes.html --> + <module name="AnonInnerLength"> + <property name="max" value="40"/> + </module> + <module name="ExecutableStatementCount"> + <property name="max" value="50"/> + </module> + <module name="FileLength"/> + <module name="LineLength"> + <property name="max" value="115"/> + </module> + <module name="MethodLength"> + <property name="max" value="150"/> + <property name="countEmpty" value="false"/> + </module> + <module name="ParameterNumber"> + <property name="max" value="7"/> + </module> + + <!-- Checks for whitespace --> + <!-- See http://checkstyle.sf.net/config_whitespace.html --> + <module name="EmptyForIteratorPad"/> + <module name="EmptyForInitializerPad"/> + <module name="MethodParamPad"/> + <module name="NoWhitespaceAfter"> + <property name="tokens" value="ARRAY_INIT,BNOT,DEC,DOT,INC,LNOT,UNARY_MINUS,UNARY_PLUS"/> + </module> + <module name="NoWhitespaceBefore"/> + <module name="OperatorWrap"/> + <module name="ParenPad"/> + <module name="TypecastParenPad"/> + <module name="TabCharacter"/> + <module name="WhitespaceAfter"> + <property name="tokens" value="COMMA, SEMI"/> + </module> + <module name="WhitespaceAround"> + <property name="tokens" + value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LCURLY, LE, LITERAL_ASSERT, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN,TYPE_EXTENSION_AND"/> + </module> + + + <!-- Modifier Checks --> + <!-- See http://checkstyle.sf.net/config_modifiers.html --> + <module name="ModifierOrder"/> + <module name="RedundantModifier"/> + + + <!-- Checks for blocks. You know, those {}'s --> + <!-- See http://checkstyle.sf.net/config_blocks.html --> + <module name="AvoidNestedBlocks"> + <property name="allowInSwitchCase" value="true"/> + </module> + <module name="EmptyBlock"> + <property name="option" value="text"/> + </module> + <module name="LeftCurly"/> + <module name="NeedBraces"/> + <module name="RightCurly"/> + + + <!-- Checks for common coding problems --> + <!-- See http://checkstyle.sf.net/config_coding.html --> + <!--<module name="ArrayTrailingComma"/>--> + <!--<module name="AvoidInlineConditionals"/>--> + <module name="CovariantEquals"/> + <module name="DoubleCheckedLocking"/> + <module name="EmptyStatement"/> + <module name="EqualsHashCode"/> + <!--<module name="FinalLocalVariable"/>--> + <module name="HiddenField"> + <property name="ignoreConstructorParameter" value="true"/> + <property name="ignoreSetter" value="true"/> + <property name="ignoreAbstractMethods" value="true"/> + </module> + <module name="IllegalInstantiation"/> + <!--<module name="IllegalToken"/>--> + <!--<module name="IllegalTokenText"/>--> + <!--<module name="InnerAssignment"/>--> + <!--<module name="MagicNumber"/>--> + <module name="MissingSwitchDefault"/> + <module name="ModifiedControlVariable"/> + <module name="SimplifyBooleanExpression"/> + <module name="SimplifyBooleanReturn"/> + <module name="StringLiteralEquality"/> + <module name="NestedIfDepth"> + <property name="max" value="3"/> + </module> + <module name="NestedTryDepth"> + <property name="max" value="3"/> + </module> + <module name="SuperClone"/> + <module name="SuperFinalize"/> + <!--<module name="IllegalCatch"/>--> + <module name="IllegalThrows"> + <property name="illegalClassNames" value="java.lang.Error,java.lang.RuntimeException"/> + </module> + <!--<module name="RedundantThrows"/>--> + <module name="PackageDeclaration"/> + <module name="JUnitTestCase"/> + <module name="ReturnCount"> + <property name="max" value="6"/> + </module> + + <module name="IllegalType"> + <property name="format" value="^xxx$"/> + </module> + <module name="DeclarationOrder"/> + <!--<module name="ParameterAssignment"/>--> + <module name="ExplicitInitialization"/> + <module name="DefaultComesLast"/> + <!--<module name="MissingCtor"/>--> + <module name="FallThrough"/> + <!--<module name="MultipleStringLiterals"/>--> + <module name="MultipleVariableDeclarations"/> + <!--<module name="RequireThis"/>--> + <module name="UnnecessaryParentheses"/> + + + <!-- Checks for class design --> + <!-- See http://checkstyle.sf.net/config_design.html --> + <!--<module name="DesignForExtension"/>--> + <module name="FinalClass"/> + <module name="HideUtilityClassConstructor"/> + <module name="InterfaceIsType"/> + <module name="MutableException"/> + <module name="ThrowsCount"> + <property name="max" value="5"/> + </module> + <module name="VisibilityModifier"> + <property name="protectedAllowed" value="true"/> + <property name="packageAllowed" value="true"/> + </module> + + + <!-- Metrics checks. --> + <!-- See http://checkstyle.sf.net/config_metrics.html --> + <module name="BooleanExpressionComplexity"> + <property name="max" value="6"/> + </module> + <!--<module name="ClassDataAbstractionCoupling"/>--> + <!--<module name="ClassFanOutComplexity"/>--> + <!--<module name="CyclomaticComplexity"/>--> + <!--<module name="NPathComplexity"/>--> + <module name="JavaNCSS"> + <property name="methodMaximum" value="75"/> + </module> + + + <!-- Miscellaneous other checks. --> + <!-- See http://checkstyle.sf.net/config_misc.html --> + <!-- + <module name="ArrayTypeStyle"/> + <module name="FinalParameters"/> + --> + <!-- + <module name="GenericIllegalRegexp"> + <property name="format" value="\s+$"/> + <property name="message" value="Line has trailing spaces."/> + </module> + --> + <module name="TodoComment"> + <property name="format" value="WARNING"/> + </module> + + <module name="UpperEll"/> + + <!--Assert statement may have side effects:--> + <module name="DescendantToken"> + <property name="tokens" value="LITERAL_ASSERT"/> + <property name="limitedTokens" + value="ASSIGN,DEC,INC,POST_DEC,POST_INC,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,DIV_ASSIGN,MOD_ASSIGN,BSR_ASSIGN,SR_ASSIGN,SL_ASSIGN,BAND_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN"/> + <property name="maximumNumber" value="0"/> + </module> + + <!--<module name="UncommentedMain"/>--> + <module name="TrailingComment"/> + <module name="Indentation"> + <property name="caseIndent" value="0"/> + </module> + <!--<module name="RequiredRegexp">--> + </module> + +</module> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/.ruleset new file mode 100644 index 0000000000..ac8671859d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/.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-M2/sca/services/bindings/binding.jsonrpc/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/pom.xml new file mode 100644 index 0000000000..4fede9927d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/pom.xml @@ -0,0 +1,59 @@ +<?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 xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <parent> + <groupId>org.apache.tuscany.sca.services.bindings</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>binding-jsonrpc</artifactId> + <name>Apache Tuscany Binding for JSON-RPC</name> + <description>Implementation of the SCA JSON-RPC Binding</description> + + <dependencies> + + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>com.metaparadigm</groupId> + <artifactId>json-rpc</artifactId> + <version>1.0</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>tomcat</groupId> + <artifactId>servlet-api</artifactId> + <version>5.0.18</version> + <scope>provided</scope> + </dependency> + + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBinding.java new file mode 100644 index 0000000000..101bfde6c2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBinding.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.binding.jsonrpc; + +import org.apache.tuscany.spi.model.Binding; + +/** + * Represents a binding to an RMI service. + * + * @version $Rev$ $Date$ + */ +public class JSONRPCBinding extends Binding { + private String uri; + + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBindingBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBindingBuilder.java new file mode 100644 index 0000000000..85654f1104 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBindingBuilder.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.binding.jsonrpc; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.BindingBuilderExtension; +import org.apache.tuscany.spi.host.ServletHost; +import org.apache.tuscany.spi.model.BoundServiceDefinition; + +/** + * Builds a Service for JSON-RPC binding. + * + * @version $Rev$ $Date$ + */ +public class JSONRPCBindingBuilder extends BindingBuilderExtension<JSONRPCBinding> { + + private ServletHost servletHost; + + @Autowire() + public void setServletHost(ServletHost servletHost) { + this.servletHost = servletHost; + } + + protected Class<JSONRPCBinding> getBindingType() { + return JSONRPCBinding.class; + } + + @SuppressWarnings("unchecked") + public Service build(CompositeComponent parent, + BoundServiceDefinition<JSONRPCBinding> serviceDefinition, + DeploymentContext deploymentContext) { + Class<?> interfaze = serviceDefinition.getServiceContract().getInterfaceClass(); + + return new JSONRPCService(serviceDefinition.getName(), interfaze, parent, wireService, servletHost); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBindingLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBindingLoader.java new file mode 100644 index 0000000000..9f2a35d912 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCBindingLoader.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.binding.jsonrpc; + +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.osoa.sca.annotations.Scope; + +/** + * Loader for handling <binding.jsonrpc> elements. + * + * @version $Rev$ $Date$ + */ +@Scope("MODULE") +public class JSONRPCBindingLoader extends LoaderExtension<JSONRPCBinding> { + public static final QName BINDING_JSON = new QName(XML_NAMESPACE_1_0, "binding.jsonrpc"); + + public JSONRPCBindingLoader(@Autowire + LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return BINDING_JSON; + } + + public JSONRPCBinding load(CompositeComponent parent, XMLStreamReader reader, DeploymentContext deploymentContext) throws XMLStreamException, + LoaderException { + + return new JSONRPCBinding(); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCEntryPointServlet.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCEntryPointServlet.java new file mode 100644 index 0000000000..c7afc4742e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCEntryPointServlet.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.jsonrpc; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import com.metaparadigm.jsonrpc.JSONRPCBridge; +import com.metaparadigm.jsonrpc.JSONRPCServlet; + +/** + * + * + */ +public class JSONRPCEntryPointServlet extends JSONRPCServlet { + private static final long serialVersionUID = 1L; + + String serviceName; + + Object serviceInstance; + + public JSONRPCEntryPointServlet(String serviceName, Object serviceInstance) { + this.serviceName = serviceName; + this.serviceInstance = serviceInstance; + + } + + /* + * (non-Javadoc) + * + * @see com.metaparadigm.jsonrpc.JSONRPCServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassCastException { + + /* + * Create a new bridge for every request to aviod all the problems with JSON-RPC-Java storing the bridge in the session + */ + HttpSession session = request.getSession(); + try { + + JSONRPCBridge jsonrpcBridge = new JSONRPCBridge(); + jsonrpcBridge.registerObject(serviceName, serviceInstance); + session.setAttribute("JSONRPCBridge", jsonrpcBridge); + + super.service(request, response); + + } finally { + session.removeAttribute("JSONRPCBridge"); + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCService.java new file mode 100644 index 0000000000..58d1d087ac --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/JSONRPCService.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.binding.jsonrpc; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.host.ServletHost; +import org.apache.tuscany.spi.wire.WireService; +import org.osoa.sca.annotations.Destroy; + +/** + * @version $Rev$ $Date$ + */ +public class JSONRPCService extends ServiceExtension { + private ServletHost servletHost; + + public JSONRPCService(String theName, Class<?> interfaze, CompositeComponent parent, WireService wireService, ServletHost servletHost) { + + super(theName, interfaze, parent, wireService); + + this.servletHost = servletHost; + } + + public void start() { + super.start(); + + JSONRPCEntryPointServlet servlet = new JSONRPCEntryPointServlet(getName(), this.getServiceInstance()); + servletHost.registerMapping("/" + getName(), servlet); + servletHost.registerMapping("/SCA/scripts", new ScriptGetterServlet()); + } + + @Destroy + public void stop() { + servletHost.unregisterMapping("/" + getName()); + servletHost.unregisterMapping("/SCA/scripts"); + + super.stop(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/ScriptGetterServlet.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/ScriptGetterServlet.java new file mode 100644 index 0000000000..8f8a96df20 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/java/org/apache/tuscany/binding/jsonrpc/ScriptGetterServlet.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.binding.jsonrpc; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class ScriptGetterServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + // private static final String SCA_INIT_JS = "SCA = new JSONRpcClient(\"services/HelloWorldService\");"; + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + URL url = getClass().getResource("jsonrpc.js"); + InputStream is = url.openStream(); + writeToStream(response, is); + + // writeToStream(response, new ByteArrayInputStream(SCA_INIT_JS.getBytes())); + } + + private void writeToStream(HttpServletResponse response, InputStream is) throws IOException { + ServletOutputStream os = response.getOutputStream(); + int i; + while ((i = is.read()) != -1) { // NOPMD + os.write(i); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/binding.jsonrpc.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/binding.jsonrpc.scdl new file mode 100644 index 0000000000..4081d437c3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/binding.jsonrpc.scdl @@ -0,0 +1,42 @@ +<?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. +--> +<!-- + Default system configuration for the launcher environment. + + $Rev$ $Date$ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + name="org.apache.tuscany.binding.jsonrpc"> + + <!-- dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <groupId>com.metaparadigm</groupId> + <name>json-rpc</name> + <version>1.0</version> + </dependency --> + + <component name="binding.jsonrpc.bindingLoader"> + <system:implementation.system class="org.apache.tuscany.binding.jsonrpc.JSONRPCBindingLoader"/> + </component> + + <component name="binding.jsonrpc.bindingBuilder"> + <system:implementation.system class="org.apache.tuscany.binding.jsonrpc.JSONRPCBindingBuilder"/> + </component> +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..aec9bb440b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,43 @@ +<?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. +--> +<!-- + Default system configuration for the launcher environment. + + $Rev$ $Date$ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + name="org.apache.tuscany.binding.jsonrpc"> + + <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <group>com.metaparadigm</group> + <name>json-rpc</name> + <version>1.0</version> + </dependency> + + <component name="binding.jsonrpc.bindingLoader"> + <system:implementation.system class="org.apache.tuscany.binding.jsonrpc.JSONRPCBindingLoader"/> + </component> + + <component name="binding.jsonrpc.bindingBuilder"> + <system:implementation.system class="org.apache.tuscany.binding.jsonrpc.JSONRPCBindingBuilder"/> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/jsonrpc_extension.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/jsonrpc_extension.scdl new file mode 100644 index 0000000000..4081d437c3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/META-INF/sca/jsonrpc_extension.scdl @@ -0,0 +1,42 @@ +<?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. +--> +<!-- + Default system configuration for the launcher environment. + + $Rev$ $Date$ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + name="org.apache.tuscany.binding.jsonrpc"> + + <!-- dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <groupId>com.metaparadigm</groupId> + <name>json-rpc</name> + <version>1.0</version> + </dependency --> + + <component name="binding.jsonrpc.bindingLoader"> + <system:implementation.system class="org.apache.tuscany.binding.jsonrpc.JSONRPCBindingLoader"/> + </component> + + <component name="binding.jsonrpc.bindingBuilder"> + <system:implementation.system class="org.apache.tuscany.binding.jsonrpc.JSONRPCBindingBuilder"/> + </component> +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/org/apache/tuscany/binding/jsonrpc/jsonrpc.js b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/org/apache/tuscany/binding/jsonrpc/jsonrpc.js new file mode 100644 index 0000000000..2b9efbb55c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.jsonrpc/src/main/resources/org/apache/tuscany/binding/jsonrpc/jsonrpc.js @@ -0,0 +1,484 @@ +/* + * JSON-RPC JavaScript client + * + * $Id: jsonrpc.js,v 1.36.2.3 2006/03/08 15:09:37 mclark Exp $ + * + * Copyright (c) 2003-2004 Jan-Klaas Kollhof + * Copyright (c) 2005 Michael Clark, Metaparadigm Pte Ltd + * + * This code is based on Jan-Klaas' JavaScript o lait library (jsolait). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + + +/* escape a character */ + +escapeJSONChar = +function escapeJSONChar(c) +{ + if(c == "\"" || c == "\\") return "\\" + c; + else if (c == "\b") return "\\b"; + else if (c == "\f") return "\\f"; + else if (c == "\n") return "\\n"; + else if (c == "\r") return "\\r"; + else if (c == "\t") return "\\t"; + var hex = c.charCodeAt(0).toString(16); + if(hex.length == 1) return "\\u000" + hex; + else if(hex.length == 2) return "\\u00" + hex; + else if(hex.length == 3) return "\\u0" + hex; + else return "\\u" + hex; +}; + + +/* encode a string into JSON format */ + +escapeJSONString = +function escapeJSONString(s) +{ + /* The following should suffice but Safari's regex is b0rken + (doesn't support callback substitutions) + return "\"" + s.replace(/([^\u0020-\u007f]|[\\\"])/g, + escapeJSONChar) + "\""; + */ + + /* Rather inefficient way to do it */ + var parts = s.split(""); + for(var i=0; i < parts.length; i++) { + var c =parts[i]; + if(c == '"' || + c == '\\' || + c.charCodeAt(0) < 32 || + c.charCodeAt(0) >= 128) + parts[i] = escapeJSONChar(parts[i]); + } + return "\"" + parts.join("") + "\""; +}; + + +/* Marshall objects to JSON format */ + +toJSON = function toJSON(o) +{ + if(o == null) { + return "null"; + } else if(o.constructor == String) { + return escapeJSONString(o); + } else if(o.constructor == Number) { + return o.toString(); + } else if(o.constructor == Boolean) { + return o.toString(); + } else if(o.constructor == Date) { + return '{javaClass: "java.util.Date", time: ' + o.valueOf() +'}'; + } else if(o.constructor == Array) { + var v = []; + for(var i = 0; i < o.length; i++) v.push(toJSON(o[i])); + return "[" + v.join(", ") + "]"; + } else { + var v = []; + for(attr in o) { + if(o[attr] == null) v.push("\"" + attr + "\": null"); + else if(typeof o[attr] == "function"); /* skip */ + else v.push(escapeJSONString(attr) + ": " + toJSON(o[attr])); + } + return "{" + v.join(", ") + "}"; + } +}; + + +/* JSONRpcClient constructor */ + +JSONRpcClient = +function JSONRpcClient_ctor(serverURL, user, pass, objectID) +{ + this.serverURL = serverURL; + this.user = user; + this.pass = pass; + this.objectID = objectID; + + /* Add standard methods */ + if(this.objectID) { + this._addMethods(["listMethods"]); + var req = this._makeRequest("listMethods", []); + } else { + this._addMethods(["system.listMethods"]); + var req = this._makeRequest("system.listMethods", []); + } + var m = this._sendRequest(req); + this._addMethods(m); +}; + + +/* JSONRpcCLient.Exception */ + +JSONRpcClient.Exception = +function JSONRpcClient_Exception_ctor(code, message, javaStack) +{ + this.code = code; + var name; + if(javaStack) { + this.javaStack = javaStack; + var m = javaStack.match(/^([^:]*)/); + if(m) name = m[0]; + } + if(name) this.name = name; + else this.name = "JSONRpcClientException"; + this.message = message; +}; + +JSONRpcClient.Exception.CODE_REMOTE_EXCEPTION = 490; +JSONRpcClient.Exception.CODE_ERR_CLIENT = 550; +JSONRpcClient.Exception.CODE_ERR_PARSE = 590; +JSONRpcClient.Exception.CODE_ERR_NOMETHOD = 591; +JSONRpcClient.Exception.CODE_ERR_UNMARSHALL = 592; +JSONRpcClient.Exception.CODE_ERR_MARSHALL = 593; + +JSONRpcClient.Exception.prototype = new Error(); + +JSONRpcClient.Exception.prototype.toString = +function JSONRpcClient_Exception_toString(code, msg) +{ + return this.name + ": " + this.message; +}; + + +/* Default top level exception handler */ + +JSONRpcClient.default_ex_handler = +function JSONRpcClient_default_ex_handler(e) { alert(e); }; + + +/* Client settable variables */ + +JSONRpcClient.toplevel_ex_handler = JSONRpcClient.default_ex_handler; +JSONRpcClient.profile_async = false; +JSONRpcClient.max_req_active = 1; +JSONRpcClient.requestId = 1; + + +/* JSONRpcClient implementation */ + +JSONRpcClient.prototype._createMethod = +function JSONRpcClient_createMethod(methodName) +{ + var fn=function() + { + var args = []; + var callback = null; + for(var i=0;i<arguments.length;i++) args.push(arguments[i]); + if(typeof args[0] == "function") callback = args.shift(); + var req = fn.client._makeRequest.call(fn.client, fn.methodName, + args, callback); + if(callback == null) { + return fn.client._sendRequest.call(fn.client, req); + } else { + JSONRpcClient.async_requests.push(req); + JSONRpcClient.kick_async(); + return req.requestId; + } + }; + fn.client = this; + fn.methodName = methodName; + return fn; +}; + +JSONRpcClient.prototype._addMethods = +function JSONRpcClient_addMethods(methodNames) +{ + for(var i=0; i<methodNames.length; i++) { + var obj = this; + var names = methodNames[i].split("."); + for(var n=0; n<names.length-1; n++) { + var name = names[n]; + if(obj[name]) { + obj = obj[name]; + } else { + obj[name] = new Object(); + obj = obj[name]; + } + } + var name = names[names.length-1]; + if(!obj[name]) { + var method = this._createMethod(methodNames[i]); + obj[name] = method; + } + } +}; + +JSONRpcClient._getCharsetFromHeaders = +function JSONRpcClient_getCharsetFromHeaders(http) +{ + try { + var contentType = http.getResponseHeader("Content-type"); + var parts = contentType.split(/\s*;\s*/); + for(var i =0; i < parts.length; i++) { + if(parts[i].substring(0, 8) == "charset=") + return parts[i].substring(8, parts[i].length); + } + } catch (e) {} + return "UTF-8"; /* default */ +}; + +/* Async queue globals */ +JSONRpcClient.async_requests = []; +JSONRpcClient.async_inflight = {}; +JSONRpcClient.async_responses = []; +JSONRpcClient.async_timeout = null; +JSONRpcClient.num_req_active = 0; + +JSONRpcClient._async_handler = +function JSONRpcClient_async_handler() +{ + JSONRpcClient.async_timeout = null; + + while(JSONRpcClient.async_responses.length > 0) { + var res = JSONRpcClient.async_responses.shift(); + if(res.canceled) continue; + if(res.profile) res.profile.dispatch = new Date(); + try { + res.cb(res.result, res.ex, res.profile); + } catch(e) { + JSONRpcClient.toplevel_ex_handler(e); + } + } + + while(JSONRpcClient.async_requests.length > 0 && + JSONRpcClient.num_req_active < JSONRpcClient.max_req_active) { + var req = JSONRpcClient.async_requests.shift(); + if(req.canceled) continue; + req.client._sendRequest.call(req.client, req); + } +}; + +JSONRpcClient.kick_async = +function JSONRpcClient_kick_async() +{ + if(JSONRpcClient.async_timeout == null) + JSONRpcClient.async_timeout = + setTimeout(JSONRpcClient._async_handler, 0); +}; + +JSONRpcClient.cancelRequest = +function JSONRpcClient_cancelRequest(requestId) +{ + /* If it is in flight then mark it as canceled in the inflight map + and the XMLHttpRequest callback will discard the reply. */ + if(JSONRpcClient.async_inflight[requestId]) { + JSONRpcClient.async_inflight[requestId].canceled = true; + return true; + } + + /* If its not in flight yet then we can just mark it as canceled in + the the request queue and it will get discarded before being sent. */ + for(var i in JSONRpcClient.async_requests) { + if(JSONRpcClient.async_requests[i].requestId == requestId) { + JSONRpcClient.async_requests[i].canceled = true; + return true; + } + } + + /* It may have returned from the network and be waiting for its callback + to be dispatched, so mark it as canceled in the response queue + and the response will get discarded before calling the callback. */ + for(var i in JSONRpcClient.async_responses) { + if(JSONRpcClient.async_responses[i].requestId == requestId) { + JSONRpcClient.async_responses[i].canceled = true; + return true; + } + } + + return false; +}; + +JSONRpcClient.prototype._makeRequest = +function JSONRpcClient_makeRequest(methodName, args, cb) +{ + var req = {}; + req.client = this; + req.requestId = JSONRpcClient.requestId++; + + var obj = {}; + obj.id = req.requestId; + if (this.objectID) + obj.method = ".obj#" + this.objectID + "." + methodName; + else + obj.method = methodName; + obj.params = args; + + if (cb) req.cb = cb; + if (JSONRpcClient.profile_async) + req.profile = { "submit": new Date() }; + req.data = toJSON(obj); + + return req; +}; + +JSONRpcClient.prototype._sendRequest = +function JSONRpcClient_sendRequest(req) +{ + if(req.profile) req.profile.start = new Date(); + + /* Get free http object from the pool */ + var http = JSONRpcClient.poolGetHTTPRequest(); + JSONRpcClient.num_req_active++; + + /* Send the request */ + if (typeof(this.user) == "undefined") { + http.open("POST", this.serverURL, (req.cb != null)); + } else { + http.open("POST", this.serverURL, (req.cb != null), this.user, this.pass); + } + + /* setRequestHeader is missing in Opera 8 Beta */ + try { http.setRequestHeader("Content-type", "text/plain"); } catch(e) {} + + /* Construct call back if we have one */ + if(req.cb) { + var self = this; + http.onreadystatechange = function() { + if(http.readyState == 4) { + http.onreadystatechange = function () {}; + var res = { "cb": req.cb, "result": null, "ex": null}; + if (req.profile) { + res.profile = req.profile; + res.profile.end = new Date(); + } + try { res.result = self._handleResponse(http); } + catch(e) { res.ex = e; } + if(!JSONRpcClient.async_inflight[req.requestId].canceled) + JSONRpcClient.async_responses.push(res); + delete JSONRpcClient.async_inflight[req.requestId]; + JSONRpcClient.kick_async(); + } + }; + } else { + http.onreadystatechange = function() {}; + } + + JSONRpcClient.async_inflight[req.requestId] = req; + + try { + http.send(req.data); + } catch(e) { + JSONRpcClient.poolReturnHTTPRequest(http); + JSONRpcClient.num_req_active--; + throw new JSONRpcClient.Exception + (JSONRpcClient.Exception.CODE_ERR_CLIENT, "Connection failed"); + } + + if(!req.cb) return this._handleResponse(http); +}; + +JSONRpcClient.prototype._handleResponse = +function JSONRpcClient_handleResponse(http) +{ + /* Get the charset */ + if(!this.charset) { + this.charset = JSONRpcClient._getCharsetFromHeaders(http); + } + + /* Get request results */ + var status, statusText, data; + try { + status = http.status; + statusText = http.statusText; + data = http.responseText; + } catch(e) { + JSONRpcClient.poolReturnHTTPRequest(http); + JSONRpcClient.num_req_active--; + JSONRpcClient.kick_async(); + throw new JSONRpcClient.Exception + (JSONRpcClient.Exception.CODE_ERR_CLIENT, "Connection failed"); + } + + /* Return http object to the pool; */ + JSONRpcClient.poolReturnHTTPRequest(http); + JSONRpcClient.num_req_active--; + + /* Unmarshall the response */ + if(status != 200) { + throw new JSONRpcClient.Exception(status, statusText); + } + var obj; + try { + eval("obj = " + data); + } catch(e) { + throw new JSONRpcClient.Exception(550, "error parsing result"); + } + if(obj.error) + throw new JSONRpcClient.Exception(obj.error.code, obj.error.msg, + obj.error.trace); + var res = obj.result; + + /* Handle CallableProxy */ + if(res && res.objectID && res.JSONRPCType == "CallableReference") + return new JSONRpcClient(this.serverURL, this.user, + this.pass, res.objectID); + + return res; +}; + + +/* XMLHttpRequest wrapper code */ + +/* XMLHttpRequest pool globals */ +JSONRpcClient.http_spare = []; +JSONRpcClient.http_max_spare = 8; + +JSONRpcClient.poolGetHTTPRequest = +function JSONRpcClient_pool_getHTTPRequest() +{ + if(JSONRpcClient.http_spare.length > 0) { + return JSONRpcClient.http_spare.pop(); + } + return JSONRpcClient.getHTTPRequest(); +}; + +JSONRpcClient.poolReturnHTTPRequest = +function JSONRpcClient_poolReturnHTTPRequest(http) +{ + if(JSONRpcClient.http_spare.length >= JSONRpcClient.http_max_spare) + delete http; + else + JSONRpcClient.http_spare.push(http); +}; + +JSONRpcClient.msxmlNames = [ "MSXML2.XMLHTTP.5.0", + "MSXML2.XMLHTTP.4.0", + "MSXML2.XMLHTTP.3.0", + "MSXML2.XMLHTTP", + "Microsoft.XMLHTTP" ]; + +JSONRpcClient.getHTTPRequest = +function JSONRpcClient_getHTTPRequest() +{ + /* Mozilla XMLHttpRequest */ + try { + JSONRpcClient.httpObjectName = "XMLHttpRequest"; + return new XMLHttpRequest(); + } catch(e) {} + + /* Microsoft MSXML ActiveX */ + for (var i=0;i < JSONRpcClient.msxmlNames.length; i++) { + try { + JSONRpcClient.httpObjectName = JSONRpcClient.msxmlNames[i]; + return new ActiveXObject(JSONRpcClient.msxmlNames[i]); + } catch (e) {} + } + + /* None found */ + JSONRpcClient.httpObjectName = null; + throw new JSONRpcClient.Exception(0, "Can't create XMLHttpRequest object"); +}; + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/.ruleset new file mode 100644 index 0000000000..3886f07f2d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/.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-M2/sca/services/bindings/binding.rmi/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/LICENSE.txt new file mode 100755 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/pom.xml new file mode 100755 index 0000000000..31ef8047d4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/pom.xml @@ -0,0 +1,63 @@ +<?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 xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <parent> + <groupId>org.apache.tuscany.sca.services.bindings</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>rmi</artifactId> + <name>Apache Tuscany Binding for Java RMI</name> + <description>Implementation of the SCA RMI Binding</description> + + <dependencies> + <dependency> + <groupId>cglib</groupId> + <artifactId>cglib-nodep</artifactId> + <version>2.1_3</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>test</artifactId> + <version>${sca.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymockclassextension</artifactId> + </dependency> + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/NoRemoteMethodException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/NoRemoteMethodException.java new file mode 100644 index 0000000000..45404f087e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/NoRemoteMethodException.java @@ -0,0 +1,37 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +/** + * @version $Rev$ $Date$ + */ +public class NoRemoteMethodException extends RMIRuntimeException { + public NoRemoteMethodException() { + } + + public NoRemoteMethodException(String message) { + super(message); + } + + public NoRemoteMethodException(String message, Throwable cause) { + super(message, cause); + } + + public NoRemoteMethodException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/NoRemoteServiceException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/NoRemoteServiceException.java new file mode 100644 index 0000000000..af2d2fd582 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/NoRemoteServiceException.java @@ -0,0 +1,37 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +/** + * @version $Rev$ $Date$ + */ +public class NoRemoteServiceException extends RMIRuntimeException { + public NoRemoteServiceException() { + } + + public NoRemoteServiceException(String message) { + super(message); + } + + public NoRemoteServiceException(String message, Throwable cause) { + super(message, cause); + } + + public NoRemoteServiceException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBinding.java new file mode 100644 index 0000000000..bc8c69851e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBinding.java @@ -0,0 +1,57 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +import org.apache.tuscany.spi.model.Binding; + +/** + * Represents a binding to an RMI service. + * + * @version $Rev$ $Date$ + */ +public class RMIBinding extends Binding { + private String host; + + private String port; + + private String serviceName; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBindingBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBindingBuilder.java new file mode 100644 index 0000000000..1e2eb9633a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBindingBuilder.java @@ -0,0 +1,78 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +import java.rmi.Remote; + +import org.apache.tuscany.host.rmi.RMIHost; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.BindingBuilderExtension; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.osoa.sca.annotations.Constructor; + +/** + * Builds a Service or Reference for an RMI binding. + * + * @version $Rev$ $Date$ + */ + +public class RMIBindingBuilder extends BindingBuilderExtension<RMIBinding> { + + private RMIHost rmiHost; + + @Constructor({"rmiHost"}) + public RMIBindingBuilder(@Autowire RMIHost rHost) { + this.rmiHost = rHost; + } + + protected Class<RMIBinding> getBindingType() { + return RMIBinding.class; + } + + @SuppressWarnings({"unchecked"}) + public Service build(CompositeComponent parent, + BoundServiceDefinition<RMIBinding> boundServiceDefinition, + DeploymentContext deploymentContext) { + + Class intf = boundServiceDefinition.getServiceContract().getInterfaceClass(); + + return new RMIService<Remote>(boundServiceDefinition.getName(), parent, wireService, rmiHost, + boundServiceDefinition.getBinding().getHost(), boundServiceDefinition.getBinding().getPort(), + boundServiceDefinition.getBinding().getServiceName(), intf); + } + + @SuppressWarnings({"unchecked"}) + public Reference build(CompositeComponent parent, + BoundReferenceDefinition<RMIBinding> boundReferenceDefinition, + DeploymentContext deploymentContext) { + String name = boundReferenceDefinition.getName(); + String host = boundReferenceDefinition.getBinding().getHost(); + String port = boundReferenceDefinition.getBinding().getPort(); + String svcName = boundReferenceDefinition.getBinding().getServiceName(); + // Class<?> interfaze = boundReferenceDefinition.getServiceContract().getInterfaceClass(); + + return new RMIReference(name, parent, wireService, rmiHost, host, port, svcName, + boundReferenceDefinition.getServiceContract().getInterfaceClass()); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBindingLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBindingLoader.java new file mode 100755 index 0000000000..bd9b165b6d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIBindingLoader.java @@ -0,0 +1,64 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.osoa.sca.annotations.Scope; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; + +/** + * Loader for handling <binding.rmi> elements. + * + * @version $Rev$ $Date$ + */ +@Scope("MODULE") +public class RMIBindingLoader extends LoaderExtension<RMIBinding> { + public static final QName BINDING_RMI = new QName( + "http://incubator.apache.org/tuscany/xmlns/binding/rmi/1.0-incubator-M2", "binding.rmi"); + + public RMIBindingLoader(@Autowire LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return BINDING_RMI; + } + + public RMIBinding load(CompositeComponent parent, + XMLStreamReader reader, + DeploymentContext deploymentContext) throws XMLStreamException, LoaderException { + String host = reader.getAttributeValue(null, "host"); + String port = reader.getAttributeValue(null, "port"); + String svcName = reader.getAttributeValue(null, "serviceName"); + LoaderUtil.skipToEndElement(reader); + RMIBinding binding = new RMIBinding(); + binding.setHost(host); + binding.setPort(port); + binding.setServiceName(svcName); + return binding; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIInvoker.java new file mode 100644 index 0000000000..afd1992d20 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIInvoker.java @@ -0,0 +1,66 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.rmi.Remote; + +import org.apache.tuscany.host.rmi.RMIHost; +import org.apache.tuscany.host.rmi.RMIHostException; +import org.apache.tuscany.spi.extension.TargetInvokerExtension; + +/** + * Invoke an RMI reference. + * + * @version $Rev$ $Date$ + */ +public class RMIInvoker extends TargetInvokerExtension { + private Method remoteMethod; + private String host; + private String port; + private String svcName; + private RMIHost rmiHost; + private Remote proxy; + + public RMIInvoker(RMIHost rmiHost, String host, String port, String svcName, Method remoteMethod) { + // assert remoteMethod.isAccessible(); + this.remoteMethod = remoteMethod; + this.host = host; + this.port = port; + this.svcName = svcName; + this.rmiHost = rmiHost; + } + + public Object invokeTarget(Object payload) throws InvocationTargetException { + try { + if (proxy == null) { + proxy = rmiHost.findService(host, port, svcName); + // proxy = Naming.lookup(serviceURI); + } + return remoteMethod.invoke(proxy, (Object[]) payload); + } catch (RMIHostException e) { + // the method we are passed must be accessible + throw new AssertionError(e); + } catch (IllegalAccessException e) { + // the method we are passed must be accessible + throw new AssertionError(e); + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIReference.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIReference.java new file mode 100644 index 0000000000..5e810892d9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIReference.java @@ -0,0 +1,87 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +import static org.apache.tuscany.spi.idl.java.JavaIDLUtils.findMethod; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.extension.ReferenceExtension; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; + +import org.apache.tuscany.host.rmi.RMIHost; + +/** + * @version $Rev$ $Date$ + */ +public class RMIReference<T> extends ReferenceExtension { + private final String host; + + private final String port; + + private final String svcName; + + private RMIHost rmiHost; + + public RMIReference(String name, + CompositeComponent parent, + WireService wireService, + RMIHost rmiHost, + String host, + String port, + String svcName, + Class<T> service) { + super(name, service, parent, wireService); + this.host = host; + this.port = port; + this.svcName = svcName; + this.rmiHost = rmiHost; + } + + public TargetInvoker createTargetInvoker(ServiceContract contract, Operation operation) { + try { + /*Remote proxy = getProxy(); + Method remoteMethod = proxy.getClass().getMethod(operation.getName(), + (Class[]) operation.getParameterTypes()); + return new RMIInvoker(proxy, remoteMethod); + */ + Method method = findMethod(operation, contract.getInterfaceClass().getMethods()); + Method remoteMethod = + getInterface().getMethod(operation.getName(), (Class[]) method.getParameterTypes()); + return new RMIInvoker(rmiHost, host, port, svcName, remoteMethod); + } catch (NoSuchMethodException e) { + throw new NoRemoteMethodException(operation.toString(), e); + } + } + + /*protected Remote getProxy() { + try { + // todo do we need to cache this result? + return Naming.lookup(uri); + } catch (NotBoundException e) { + throw new NoRemoteServiceException(uri); + } catch (MalformedURLException e) { + throw new NoRemoteServiceException(uri); + } catch (RemoteException e) { + throw new NoRemoteServiceException(uri); + } + }*/ +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIRuntimeException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIRuntimeException.java new file mode 100644 index 0000000000..c36dec4531 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIRuntimeException.java @@ -0,0 +1,39 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +import org.apache.tuscany.api.TuscanyRuntimeException; + +/** + * @version $Rev$ $Date$ + */ +public abstract class RMIRuntimeException extends TuscanyRuntimeException { + protected RMIRuntimeException() { + } + + protected RMIRuntimeException(String message) { + super(message); + } + + protected RMIRuntimeException(String message, Throwable cause) { + super(message, cause); + } + + protected RMIRuntimeException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIService.java new file mode 100644 index 0000000000..0de833801f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RMIService.java @@ -0,0 +1,160 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +import java.lang.reflect.Method; +import java.rmi.Remote; +import java.rmi.server.UnicastRemoteObject; + +import net.sf.cglib.asm.ClassWriter; +import net.sf.cglib.asm.Constants; +import net.sf.cglib.asm.Type; +import net.sf.cglib.proxy.Enhancer; + +import org.apache.tuscany.host.rmi.RMIHost; +import org.apache.tuscany.host.rmi.RMIHostException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.wire.WireService; + +/** + * @version $Rev$ $Date$ + */ +public class RMIService<T extends Remote> extends ServiceExtension { + + public static final String URI_PREFIX = "//localhost"; + public static final String SLASH = "/"; + public static final String COLON = ":"; + //private final String host; + private final String port; + private final String serviceName; + private RMIHost rmiHost; + + // need this member to morph the service interface to extend from Remote if it does not + // the base class's member variable interfaze is to be maintained to enable the connection + // of the service outbound to the component's inbound wire which requires that the service + // and the component match in their service contracts. + private Class serviceInterface; + + public RMIService(String name, + CompositeComponent parent, + WireService wireService, + RMIHost rHost, + String host, + String port, + String svcName, + Class<T> service) { + super(name, service, parent, wireService); + + this.serviceInterface = service; + this.rmiHost = rHost; + //this.host = host; + this.port = port; + this.serviceName = svcName; + } + + public void start() { + super.start(); + Remote rmiProxy = createRmiService(); + + try { + // startRMIRegistry(); + rmiHost.registerService(serviceName, + getPort(port), + rmiProxy); + // bindRmiService(uri,rmiProxy); + } catch (RMIHostException e) { + throw new NoRemoteServiceException(e); + } + } + + public void stop() { + try { + rmiHost.unregisterService(serviceName, getPort(port)); + } catch (RMIHostException e) { + throw new NoRemoteServiceException(e.getMessage()); + } + super.stop(); + } + + protected Remote createRmiService() { + Enhancer enhancer = new Enhancer(); + enhancer.setSuperclass(UnicastRemoteObject.class); + enhancer.setCallback(new RemoteMethodHandler(getHandler(), interfaze)); + + if (!Remote.class.isAssignableFrom(serviceInterface)) { + RMIServiceClassLoader classloader = + new RMIServiceClassLoader(getClass().getClassLoader()); + final byte[] byteCode = generateRemoteInterface(serviceInterface); + serviceInterface = classloader.defineClass(byteCode); + enhancer.setClassLoader(classloader); + } + enhancer.setInterfaces(new Class[]{serviceInterface}); + return (Remote) enhancer.create(); + } + + protected int getPort(String port) { + int portNumber = RMIHost.RMI_DEFAULT_PORT; + if (port != null && port.length() > 0) { + portNumber = Integer.decode(port); + } + + return portNumber; + } + + // if the interface of the component whose services must be exposed as RMI Service, does not + // implement java.rmi.Remote, then generate such an interface. This method will stop with + // just generating the bytecode. Defining the class from the byte code must tbe the responsibility + // of the caller of this method, since it requires a classloader to be created to define and load + // this interface. + protected byte[] generateRemoteInterface(Class serviceInterface) { + String interfazeName = serviceInterface.getCanonicalName(); + ClassWriter cw = new ClassWriter(false); + + String simpleName = serviceInterface.getSimpleName(); + cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_ABSTRACT + Constants.ACC_INTERFACE, + interfazeName.replace('.', '/'), "java/lang/Object", new String[]{"java/rmi/Remote"}, simpleName + ".java"); + + StringBuffer argsAndReturn = null; + Method[] methods = serviceInterface.getMethods(); + for (Method method : methods) { + argsAndReturn = new StringBuffer("("); + Class[] paramTypes = method.getParameterTypes(); + Class returnType = method.getReturnType(); + + for (Class paramType : paramTypes) { + argsAndReturn.append(Type.getType(paramType)); + } + argsAndReturn.append(")"); + argsAndReturn.append(Type.getType(returnType)); + + cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_ABSTRACT, method.getName(), argsAndReturn.toString(), + new String[]{"java/rmi/RemoteException"}, null); + } + cw.visitEnd(); + return cw.toByteArray(); + } + + private class RMIServiceClassLoader extends ClassLoader { + public RMIServiceClassLoader(ClassLoader parent) { + super(parent); + } + public Class defineClass(byte[] byteArray) { + return defineClass(null, byteArray, 0, byteArray.length); + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RemoteMethodHandler.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RemoteMethodHandler.java new file mode 100644 index 0000000000..b27c87b510 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/RemoteMethodHandler.java @@ -0,0 +1,47 @@ +/** + * + * Copyright 2006 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.binding.rmi; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.wire.WireInvocationHandler; + +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; + +public class RemoteMethodHandler implements MethodInterceptor { + public static final String FINALIZE_METHOD = "finalize"; + + private WireInvocationHandler wireHandler; + + private Class compSvcIntf; + + public RemoteMethodHandler(WireInvocationHandler handler, Class intf) { + this.wireHandler = handler; + compSvcIntf = intf; + } + + public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + // since incoming method signatures have 'remotemethod invocation' it will not match with the + // wired component's method signatures. Hence need to pull in the corresponding method from the + // component's service contract interface to make this invocation. + return wireHandler.invoke(compSvcIntf.getMethod(method.getName(), + (Class[]) method.getParameterTypes()), + args); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/host/RMIHostImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/host/RMIHostImpl.java new file mode 100644 index 0000000000..9355cf642e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/java/org/apache/tuscany/binding/rmi/host/RMIHostImpl.java @@ -0,0 +1,136 @@ +/** + * + * Copyright 2006 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.binding.rmi.host; + +import java.rmi.AlreadyBoundException; +import java.rmi.NotBoundException; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.registry.LocateRegistry; +import java.rmi.registry.Registry; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.tuscany.host.rmi.RMIHost; +import org.apache.tuscany.host.rmi.RMIHostException; +import org.apache.tuscany.host.rmi.RMIHostRuntimeException; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +/** + * This class provides an implementation for the RMI Host SPIs + */ +@Scope("MODULE") +public class RMIHostImpl implements RMIHost { + + // map of RMI registries started and running + private Map<String, Registry> rmiRegistries; + + public RMIHostImpl() { + rmiRegistries = new ConcurrentHashMap<String, Registry>(); + /* + * if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } + */ + } + + @Init(eager = true) + public void init() { + } + + public void registerService(String serviceName, int port, Remote serviceObject) throws RMIHostException, + RMIHostRuntimeException { + Registry registry; + try { + registry = rmiRegistries.get(Integer.toString(port)); + if (registry == null) { + registry = LocateRegistry.createRegistry(port); + rmiRegistries.put(Integer.toString(port), + registry); + } + registry.bind(serviceName, + serviceObject); + } catch (AlreadyBoundException e) { + throw new RMIHostException(e.getMessage()); + } catch (RemoteException e) { + RMIHostRuntimeException rmiExec = new RMIHostRuntimeException(e.getMessage()); + rmiExec.setStackTrace(e.getStackTrace()); + throw rmiExec; + } + + } + + public void registerService(String serviceName, Remote serviceObject) throws RMIHostException, + RMIHostRuntimeException { + registerService(serviceName, + RMI_DEFAULT_PORT, + serviceObject); + } + + public void unregisterService(String serviceName, int port) throws RMIHostException, + RMIHostRuntimeException { + Registry registry; + + try { + registry = rmiRegistries.get(Integer.toString(port)); + if (registry == null) { + registry = LocateRegistry.createRegistry(port); + rmiRegistries.put(Integer.toString(port), + registry); + } + registry.unbind(serviceName); + } catch (RemoteException e) { + RMIHostRuntimeException rmiExec = new RMIHostRuntimeException(e.getMessage()); + rmiExec.setStackTrace(e.getStackTrace()); + throw rmiExec; + } catch (NotBoundException e) { + throw new RMIHostException(e.getMessage()); + } + } + + public void unregisterService(String serviceName) throws RMIHostException, + RMIHostRuntimeException { + unregisterService(serviceName, + RMI_DEFAULT_PORT); + + } + + public Remote findService(String host, String port, String svcName) throws RMIHostException, + RMIHostRuntimeException { + Registry registry; + Remote remoteService = null; + host = (host == null || host.length() <= 0) ? "localhost" : host; + int portNumber = (port == null || port.length() <= 0) ? RMI_DEFAULT_PORT : Integer + .decode(port); + + try { + registry = LocateRegistry.getRegistry(host, + portNumber); + + if (registry != null) { + remoteService = registry.lookup(svcName); + } + } catch (RemoteException e) { + RMIHostRuntimeException rmiExec = new RMIHostRuntimeException(e.getMessage()); + rmiExec.setStackTrace(e.getStackTrace()); + throw rmiExec; + } catch (NotBoundException e) { + throw new RMIHostException(e.getMessage()); + } + return remoteService; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..61d6523472 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,55 @@ +<?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. + --> +<!-- + Default system configuration for the launcher environment. + + $Rev$ $Date$ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + xmlns:tuscany="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2" + name="org.apache.tuscany.binding.rmi"> + + + <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <group>org.apache.tuscany.sca.services.bindings</group> + <name>rmi</name> + <version>1.0-incubator-M2-SNAPSHOT</version> + </dependency> + + <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <group>org.apache.tuscany.sca.kernel</group> + <name>tuscany-api</name> + <version>1.0-incubator-M2-SNAPSHOT</version> + </dependency> + + <component name="binding.rmi.bindingLoader"> + <system:implementation.system class="org.apache.tuscany.binding.rmi.RMIBindingLoader"/> + </component> + + <component name="binding.rmi.bindingBuilder"> + <system:implementation.system class="org.apache.tuscany.binding.rmi.RMIBindingBuilder"/> + </component> + + <!-- RMI Host service --> + <component name="rmiHost"> + <system:implementation.system class="org.apache.tuscany.binding.rmi.host.RMIHostImpl"/> + </component> +</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/resources/META-INF/sca/rmi_extension.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/resources/META-INF/sca/rmi_extension.scdl new file mode 100644 index 0000000000..9417a1d5ad --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/main/resources/META-INF/sca/rmi_extension.scdl @@ -0,0 +1,42 @@ +<?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. + --> +<!-- + Default system configuration for the launcher environment. + + $Rev$ $Date$ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + xmlns:tuscany="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2" + name="org.apache.tuscany.binding.rmi"> + + <component name="binding.rmi.bindingLoader"> + <system:implementation.system class="org.apache.tuscany.binding.rmi.RMIBindingLoader"/> + </component> + + <component name="binding.rmi.bindingBuilder"> + <system:implementation.system class="org.apache.tuscany.binding.rmi.RMIBindingBuilder"/> + </component> + + <!-- RMI Host service --> + <component name="rmiHost"> + <system:implementation.system class="org.apache.tuscany.binding.rmi.host.RMIHostImpl"/> + </component> +</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldImpl.java new file mode 100644 index 0000000000..ef17df1e9d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldImpl.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package helloworld; + +import org.osoa.sca.annotations.Service; + +/** + * This class implements the HelloWorld service. + */ +@Service(HelloWorldService.class) +public class HelloWorldImpl implements HelloWorldService { + + public String sayHello(String name) { + return "Hello from the RMI Service to - " + name; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldRmiImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldRmiImpl.java new file mode 100644 index 0000000000..a63d8d162c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldRmiImpl.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 helloworld; + +import org.osoa.sca.annotations.Reference; +import org.osoa.sca.annotations.Service; + +/** + * This class implements the HelloWorld service. + */ +@Service(HelloWorldRmiService.class) +public class HelloWorldRmiImpl implements HelloWorldRmiService { + @Reference + private HelloWorldService extService; + + public HelloWorldService getExtService() { + return extService; + } + + @Reference + public void setExtService(HelloWorldService extService) { + this.extService = extService; + } + + public String sayRmiHello(String name) { + return extService.sayHello(name) + " thro the RMI Reference"; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldRmiService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldRmiService.java new file mode 100644 index 0000000000..b6b99f45e3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldRmiService.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 helloworld; + +/** + * This is the business interface of the HelloWorld greetings service. + */ +public interface HelloWorldRmiService { + + String sayRmiHello(String name); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldService.java new file mode 100644 index 0000000000..25f2b1da31 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/helloworld/HelloWorldService.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 helloworld; + +/** + * This is the business interface of the HelloWorld greetings service. + */ +public interface HelloWorldService { + + String sayHello(String name); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/BindingTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/BindingTestCase.java new file mode 100644 index 0000000000..7ebee2af66 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/BindingTestCase.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.rmi; + +import helloworld.HelloWorldRmiService; + +import org.apache.tuscany.test.SCATestCase; +import org.osoa.sca.CompositeContext; +import org.osoa.sca.CurrentCompositeContext; + +// TODO: renamed to XXX as it doesn't work for me +public class BindingTestCase extends SCATestCase { + private HelloWorldRmiService helloWorldRmiService; + + public void testRmiService() { + System.out.println(helloWorldRmiService.sayRmiHello("Tuscany World!")); + assertEquals("Hello from the RMI Service to - Tuscany World! thro the RMI Reference", + helloWorldRmiService.sayRmiHello("Tuscany World!")); + } + + protected void setUp() throws Exception { + addExtension("rmi.binding", + getClass().getClassLoader().getResource("META-INF/sca/rmi_extension.scdl")); + setApplicationSCDL(getClass().getClassLoader().getResource("META-INF/sca/default.scdl")); + + super.setUp(); + + CompositeContext context = CurrentCompositeContext.getContext(); + helloWorldRmiService = context.locateService(HelloWorldRmiService.class, + "HelloWorldRmiServiceComponent"); + } + + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/NoRemoteMethodExceptionTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/NoRemoteMethodExceptionTestCase.java new file mode 100644 index 0000000000..cb4911a0a5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/NoRemoteMethodExceptionTestCase.java @@ -0,0 +1,47 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.rmi;
+
+import junit.framework.TestCase;
+
+public class NoRemoteMethodExceptionTestCase extends TestCase {
+
+ public void testNoArgs() {
+ assertNotNull(new NoRemoteMethodException());
+ }
+
+ public void testMsgArg() {
+ NoRemoteMethodException e = new NoRemoteMethodException("foo");
+ assertEquals("foo", e.getMessage());
+ }
+
+ public void test2Args() {
+ Exception cause = new Exception();
+ NoRemoteMethodException e = new NoRemoteMethodException("foo", cause);
+ assertEquals("foo", e.getMessage());
+ assertEquals(cause, e.getCause());
+ }
+
+ public void testCauseArgs() {
+ Exception cause = new Exception();
+ NoRemoteMethodException e = new NoRemoteMethodException(cause);
+ assertEquals(cause, e.getCause());
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/NoRemoteServiceExceptionTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/NoRemoteServiceExceptionTestCase.java new file mode 100644 index 0000000000..a5da001ad9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/NoRemoteServiceExceptionTestCase.java @@ -0,0 +1,47 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.binding.rmi;
+
+import junit.framework.TestCase;
+
+public class NoRemoteServiceExceptionTestCase extends TestCase {
+
+ public void testNoArgs() {
+ assertNotNull(new NoRemoteServiceException());
+ }
+
+ public void testMsgArg() {
+ NoRemoteServiceException e = new NoRemoteServiceException("foo");
+ assertEquals("foo", e.getMessage());
+ }
+
+ public void test2Args() {
+ Exception cause = new Exception();
+ NoRemoteServiceException e = new NoRemoteServiceException("foo", cause);
+ assertEquals("foo", e.getMessage());
+ assertEquals(cause, e.getCause());
+ }
+
+ public void testCauseArgs() {
+ Exception cause = new Exception();
+ NoRemoteServiceException e = new NoRemoteServiceException(cause);
+ assertEquals(cause, e.getCause());
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingBuilderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingBuilderTestCase.java new file mode 100644 index 0000000000..b74be6d78b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingBuilderTestCase.java @@ -0,0 +1,48 @@ +/**
+ *
+ * Copyright 2006 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.binding.rmi;
+
+import static org.easymock.EasyMock.expect;
+import static org.easymock.classextension.EasyMock.createMock;
+import static org.easymock.classextension.EasyMock.replay;
+import junit.framework.TestCase;
+
+import org.apache.tuscany.spi.model.BoundReferenceDefinition;
+import org.apache.tuscany.spi.model.ServiceContract;
+
+public class RMIBindingBuilderTestCase extends TestCase {
+
+ public void testGetBindingType() {
+ assertEquals(RMIBinding.class, new RMIBindingBuilder(null).getBindingType());
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testBuildService() {
+ RMIBindingBuilder builder = new RMIBindingBuilder(null);
+ BoundReferenceDefinition<RMIBinding> def = createMock(BoundReferenceDefinition.class);
+ expect(def.getName()).andReturn("petra");
+ RMIBinding binding = new RMIBinding();
+ expect(def.getBinding()).andReturn(binding );
+ expect(def.getBinding()).andReturn(binding );
+ expect(def.getBinding()).andReturn(binding );
+ ServiceContract sc = createMock(ServiceContract.class);
+ expect(def.getServiceContract()).andReturn(sc);
+ replay(def);
+ Object ref = builder.build(null, def, null);
+ assertTrue(ref instanceof RMIReference);
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingLoaderTestCase.java new file mode 100644 index 0000000000..160ca19b8a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingLoaderTestCase.java @@ -0,0 +1,74 @@ +/**
+ *
+ * Copyright 2006 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.binding.rmi;
+
+import static org.easymock.EasyMock.expect;
+import static org.easymock.classextension.EasyMock.createMock;
+import static org.easymock.classextension.EasyMock.replay;
+import static org.easymock.classextension.EasyMock.verify;
+
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+import junit.framework.TestCase;
+
+import org.apache.tuscany.spi.component.CompositeComponent;
+import org.apache.tuscany.spi.deployer.DeploymentContext;
+import org.apache.tuscany.spi.loader.LoaderException;
+import org.apache.tuscany.spi.loader.LoaderRegistry;
+
+public class RMIBindingLoaderTestCase extends TestCase {
+ private CompositeComponent parent;
+
+ private XMLStreamReader reader;
+
+ private DeploymentContext deploymentContext;
+
+ private LoaderRegistry registry;
+
+ private RMIBindingLoader loader;
+
+ public void testLoad() throws LoaderException, XMLStreamException {
+ expect(reader.getAttributeValue(null, "host")).andReturn("host");
+ expect(reader.getAttributeValue(null, "port")).andReturn("0");
+ expect(reader.getAttributeValue(null, "serviceName")).andReturn("servicename");
+ expect(reader.next()).andReturn(XMLStreamConstants.END_ELEMENT);
+
+ replay(reader);
+ replay(deploymentContext);
+
+ RMIBindingLoader mockLoader = new RMIBindingLoader(registry);
+ mockLoader.load(parent, reader, deploymentContext);
+ verify(reader);
+ verify(deploymentContext);
+ }
+
+ public void testGetXMLType() throws LoaderException {
+ assertEquals(RMIBindingLoader.BINDING_RMI, loader.getXMLType());
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ registry = createMock(LoaderRegistry.class);
+ loader = new RMIBindingLoader(registry);
+
+ parent = createMock(CompositeComponent.class);
+ reader = createMock(XMLStreamReader.class);
+ deploymentContext = createMock(DeploymentContext.class);
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingTestCase.java new file mode 100644 index 0000000000..6dbb81437f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIBindingTestCase.java @@ -0,0 +1,40 @@ +/**
+ *
+ * Copyright 2006 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.binding.rmi;
+
+import junit.framework.TestCase;
+
+public class RMIBindingTestCase extends TestCase {
+
+ public void testHost() {
+ RMIBinding binding = new RMIBinding();
+ binding.setHost("foo");
+ assertEquals("foo", binding.getHost());
+ }
+
+ public void testPort() {
+ RMIBinding binding = new RMIBinding();
+ binding.setPort("foo");
+ assertEquals("foo", binding.getPort());
+ }
+
+ public void testServiceName() {
+ RMIBinding binding = new RMIBinding();
+ binding.setServiceName("foo");
+ assertEquals("foo", binding.getServiceName());
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIInvokerTestCase.java new file mode 100644 index 0000000000..72c0acacc4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIInvokerTestCase.java @@ -0,0 +1,84 @@ +/**
+ *
+ * Copyright 2006 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.binding.rmi;
+
+import static org.easymock.EasyMock.expect;
+import static org.easymock.classextension.EasyMock.createMock;
+import static org.easymock.classextension.EasyMock.replay;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.rmi.Remote;
+
+import junit.framework.TestCase;
+
+import org.apache.tuscany.host.rmi.RMIHost;
+import org.apache.tuscany.host.rmi.RMIHostException;
+import org.apache.tuscany.host.rmi.RMIHostRuntimeException;
+
+public class RMIInvokerTestCase extends TestCase {
+
+ public void testInvokeTarget() throws InvocationTargetException, RMIHostRuntimeException, RMIHostException, IllegalArgumentException,
+ IllegalAccessException, SecurityException, NoSuchMethodException {
+ Method method = Object.class.getDeclaredMethod("toString", new Class[] {});
+ RMIHost host = createMock(RMIHost.class);
+ expect(host.findService(null, null, null)).andReturn(new Remote() {
+ });
+ replay(host);
+ RMIInvoker invoker = new RMIInvoker(host, null, null, null, method);
+ assertNotNull(invoker.invokeTarget(new Object[] {}));
+ }
+
+// TODO: these don't seem to work
+// public void testInvokeTargetRMIHostException() throws InvocationTargetException, RMIHostRuntimeException, RMIHostException,
+// IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchMethodException {
+// Method method = foo.class.getDeclaredMethod("bang", new Class[] {});
+// RMIHost host = createMock(RMIHost.class);
+// expect(host.findService(null, null, null)).andReturn(new foo());
+// replay(host);
+// try {
+// new RMIInvoker(host, null, null, null, method).invokeTarget(new Object[] {});
+// fail();
+// } catch (InvocationTargetException e) {
+// // expected
+// }
+// }
+//
+// public void testInvokeTargetIllegalAccessException() throws InvocationTargetException, RMIHostRuntimeException, RMIHostException,
+// IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchMethodException {
+// Method method = foo.class.getDeclaredMethod("crash", new Class[] {});
+// RMIHost host = createMock(RMIHost.class);
+// expect(host.findService(null, null, null)).andReturn(new foo());
+// replay(host);
+// try {
+// new RMIInvoker(host, null, null, null, method).invokeTarget(new Object[] {});
+// fail();
+// } catch (InvocationTargetException e) {
+// // expected
+// }
+// }
+//
+// class foo implements Remote {
+// void crash() throws IllegalAccessException {
+// throw new IllegalAccessException();
+// }
+//
+// void bang() throws RMIHostException {
+// throw new RMIHostException();
+// }
+// }
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIReferenceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIReferenceTestCase.java new file mode 100644 index 0000000000..5c935ec38a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIReferenceTestCase.java @@ -0,0 +1,48 @@ +/**
+ *
+ * Copyright 2006 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.binding.rmi;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.apache.tuscany.spi.idl.java.JavaServiceContract;
+import org.apache.tuscany.spi.model.DataType;
+import org.apache.tuscany.spi.model.Operation;
+import org.apache.tuscany.spi.model.ServiceContract;
+
+public class RMIReferenceTestCase extends TestCase {
+
+ @SuppressWarnings("unchecked")
+ public void testCreateTargetInvoker() {
+ // TODO: this doesn't really test anything yet
+ RMIReference ref = new RMIReference(null, null, null, null, null, null, null, null);
+ ServiceContract contract = new JavaServiceContract();
+ contract.setInterfaceClass(String.class);
+ List l = new ArrayList();
+ l.add(new DataType(null, null));
+ DataType in = new DataType(null, l);
+ Operation operation = new Operation(null, in, null, null);
+ try {
+ ref.createTargetInvoker(contract, operation);
+ } catch (Exception e) {
+ // expected
+ }
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIServiceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIServiceTestCase.java new file mode 100644 index 0000000000..1386cf2c72 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RMIServiceTestCase.java @@ -0,0 +1,53 @@ +/**
+ *
+ * Copyright 2006 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.binding.rmi;
+
+import junit.framework.TestCase;
+
+import org.apache.tuscany.binding.rmi.host.RMIHostImpl;
+import org.apache.tuscany.host.rmi.RMIHostRuntimeException;
+import org.apache.tuscany.spi.wire.WireInvocationHandler;
+
+public class RMIServiceTestCase extends TestCase {
+
+ @SuppressWarnings("unchecked")
+ public void testGetPort() {
+ RMIService s = new RMIService(null, null, null, null, null, null, null, null);
+ assertEquals(0, s.getPort("0"));
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testGenerateRemoteInterface() {
+ RMIService s = new RMIService("foo27", null, null, null, null, null, null, null);
+ s.generateRemoteInterface(Runnable.class);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testCreateRmiService() {
+ RMIService s = new RMIService("bla023", null, null, new RMIHostImpl(), null, "9996", "bla", Runnable.class) {
+ public WireInvocationHandler getHandler() {
+ return null;
+ }
+ };
+ s.start();
+ try {
+ s.stop();
+ } catch (RMIHostRuntimeException e) {
+ // expected
+ }
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RemoteMethodHandlerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RemoteMethodHandlerTestCase.java new file mode 100644 index 0000000000..f5c9595aa3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/RemoteMethodHandlerTestCase.java @@ -0,0 +1,42 @@ +/**
+ *
+ * Copyright 2006 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.binding.rmi;
+
+import static org.easymock.EasyMock.expect;
+import static org.easymock.classextension.EasyMock.createMock;
+import static org.easymock.classextension.EasyMock.replay;
+
+import java.lang.reflect.Method;
+
+import junit.framework.TestCase;
+
+import org.apache.tuscany.spi.wire.WireInvocationHandler;
+
+public class RemoteMethodHandlerTestCase extends TestCase {
+
+ public void testIntercept() throws SecurityException, NoSuchMethodException, Throwable {
+ WireInvocationHandler h2 = createMock(WireInvocationHandler.class);
+ Method method = Runnable.class.getDeclaredMethod("run", new Class[]{});
+ Object[] noArgs = new Object[]{};
+ expect(h2.invoke(method, noArgs)).andReturn("foo");
+ replay(h2);
+ RemoteMethodHandler handler = new RemoteMethodHandler(h2, Runnable.class);
+ Object o = handler.intercept(null, method, noArgs, null);
+ assertEquals("foo", o);
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/host/RMIHostImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/host/RMIHostImplTestCase.java new file mode 100644 index 0000000000..08f6172f3d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/java/org/apache/tuscany/binding/rmi/host/RMIHostImplTestCase.java @@ -0,0 +1,76 @@ +/**
+ *
+ * Copyright 2006 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.binding.rmi.host;
+
+import java.rmi.Remote;
+
+import junit.framework.TestCase;
+
+import org.apache.tuscany.host.rmi.RMIHostException;
+import org.apache.tuscany.host.rmi.RMIHostRuntimeException;
+
+public class RMIHostImplTestCase extends TestCase {
+
+ public void testInit() {
+ new RMIHostImpl().init();
+ }
+
+ public void testFindServiceBadHost() throws RMIHostRuntimeException, RMIHostException {
+ try {
+ new RMIHostImpl().findService(null, "0", null);
+ fail();
+ } catch (RMIHostRuntimeException e) {
+ // expected
+ }
+ }
+
+ public void testRegisterService1() throws RMIHostRuntimeException, RMIHostException {
+ RMIHostImpl host = new RMIHostImpl();
+ host.registerService("foo1", new MockRemote());
+ host.unregisterService("foo1");
+ }
+
+ public void testRegisterService2() throws RMIHostRuntimeException, RMIHostException {
+ RMIHostImpl host = new RMIHostImpl();
+ host.registerService("bar1", 9999, new MockRemote());
+ host.unregisterService("bar1", 9999);
+ }
+
+ public void testRegisterServiceAlreadyBound() throws RMIHostRuntimeException, RMIHostException {
+ RMIHostImpl host = new RMIHostImpl();
+ host.registerService("bar2", 9997, new MockRemote());
+ try {
+ host.registerService("bar2", 9997, new MockRemote());
+ } catch (RMIHostException e) {
+ // expected
+ host.unregisterService("bar2", 9997);
+ }
+ }
+
+ public void testUnRegisterService() throws RMIHostRuntimeException, RMIHostException {
+ RMIHostImpl host = new RMIHostImpl();
+ try {
+ host.unregisterService("bar3", 9998);
+ fail();
+ } catch (RMIHostException e) {
+ // expected
+ }
+ }
+
+ private static class MockRemote implements Remote {
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/HelloWorldImpl.componentType b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/HelloWorldImpl.componentType new file mode 100644 index 0000000000..a0beb4403d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/HelloWorldImpl.componentType @@ -0,0 +1,27 @@ +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> + +<?xml version="1.0" encoding="ASCII"?> + +<componentType xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + + <service name="HelloWorldService"> + <interface.java interface="helloworld.HelloWorldService"/> + </service> +</componentType> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/HelloWorldRmiImpl.componentType b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/HelloWorldRmiImpl.componentType new file mode 100644 index 0000000000..b0e0b007a6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/HelloWorldRmiImpl.componentType @@ -0,0 +1,29 @@ +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<?xml version="1.0" encoding="ASCII"?> + +<componentType xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + + <service name="HelloWorldRmiService"> + <interface.java interface="helloworld.HelloWorldRmiService"/> + </service> + <reference name="extService"> + <interface.java interface="helloworld.HelloWorldService"/> + </reference> +</componentType> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/LICENSE.txt new file mode 100644 index 0000000000..25d78feeac --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/LICENSE.txt @@ -0,0 +1,1277 @@ + + 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. + + +APACHE TUSCANY SUBCOMPONENTS: + +The Apache Tuscany distribution includes a number of subcomponents with +separate copyright notices and license terms. Your use of the source +code for the these subcomponents is subject to the terms and +conditions of the following licenses. + +=============================================================================== + +For the Eclipse Modeling Framework component and the Celtix binding: + +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE +PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF +THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + +a) in the case of the initial Contributor, the initial code and +documentation distributed under this Agreement, and +b) in the case of each subsequent Contributor: + +i) changes to the Program, and + +ii) additions to the Program; + +where such changes and/or additions to the Program originate from and +are distributed by that particular Contributor. A Contribution +'originates' from a Contributor if it was added to the Program by such +Contributor itself or anyone acting on such Contributor's behalf. +Contributions do not include additions to the Program which: (i) are +separate modules of software distributed in conjunction with the +Program under their own license agreement, and (ii) are not derivative +works of the Program. + +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents " mean patent claims licensable by a Contributor +which are necessarily infringed by the use or sale of its Contribution +alone or when combined with the Program. + +"Program" means the Contributions distributed in accordance with this +Agreement. + +"Recipient" means anyone who receives the Program under this +Agreement, including all Contributors. + +2. GRANT OF RIGHTS + +a) Subject to the terms of this Agreement, each Contributor hereby +grants Recipient a non-exclusive, worldwide, royalty-free copyright +license to reproduce, prepare derivative works of, publicly display, +publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and +object code form. + +b) Subject to the terms of this Agreement, each Contributor hereby +grants Recipient a non-exclusive, worldwide, royalty-free patent +license under Licensed Patents to make, use, sell, offer to sell, +import and otherwise transfer the Contribution of such Contributor, if +any, in source code and object code form. This patent license shall +apply to the combination of the Contribution and the Program if, at +the time the Contribution is added by the Contributor, such addition +of the Contribution causes such combination to be covered by the +Licensed Patents. The patent license shall not apply to any other +combinations which include the Contribution. No hardware per se is +licensed hereunder. + +c) Recipient understands that although each Contributor grants the +licenses to its Contributions set forth herein, no assurances are +provided by any Contributor that the Program does not infringe the +patent or other intellectual property rights of any other entity. Each +Contributor disclaims any liability to Recipient for claims brought by +any other entity based on infringement of intellectual property rights +or otherwise. As a condition to exercising the rights and licenses +granted hereunder, each Recipient hereby assumes sole responsibility +to secure any other intellectual property rights needed, if any. For +example, if a third party patent license is required to allow +Recipient to distribute the Program, it is Recipient's responsibility +to acquire that license before distributing the Program. + +d) Each Contributor represents that to its knowledge it has sufficient +copyright rights in its Contribution, if any, to grant the copyright +license set forth in this Agreement. + +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form +under its own license agreement, provided that: + +a) it complies with the terms and conditions of this Agreement; and + +b) its license agreement: + +i) effectively disclaims on behalf of all Contributors all warranties +and conditions, express and implied, including warranties or +conditions of title and non-infringement, and implied warranties or +conditions of merchantability and fitness for a particular purpose; + +ii) effectively excludes on behalf of all Contributors all liability +for damages, including direct, indirect, special, incidental and +consequential damages, such as lost profits; + +iii) states that any provisions which differ from this Agreement are +offered by that Contributor alone and not by any other party; and + +iv) states that source code for the Program is available from such +Contributor, and informs licensees how to obtain it in a reasonable +manner on or through a medium customarily used for software exchange. + +When the Program is made available in source code form: + +a) it must be made available under this Agreement; and + +b) a copy of this Agreement must be included with each copy of the +Program. + +Contributors may not remove or alter any copyright notices contained +within the Program. + +Each Contributor must identify itself as the originator of its +Contribution, if any, in a manner that reasonably allows subsequent +Recipients to identify the originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain +responsibilities with respect to end users, business partners and the +like. While this license is intended to facilitate the commercial use +of the Program, the Contributor who includes the Program in a +commercial product offering should do so in a manner which does not +create potential liability for other Contributors. Therefore, if a +Contributor includes the Program in a commercial product offering, +such Contributor ("Commercial Contributor") hereby agrees to defend +and indemnify every other Contributor ("Indemnified Contributor") +against any losses, damages and costs (collectively "Losses") arising +from claims, lawsuits and other legal actions brought by a third party +against the Indemnified Contributor to the extent caused by the acts +or omissions of such Commercial Contributor in connection with its +distribution of the Program in a commercial product offering. The +obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. +In order to qualify, an Indemnified Contributor must: a) promptly +notify the Commercial Contributor in writing of such claim, and b) +allow the Commercial Contributor to control, and cooperate with the +Commercial Contributor in, the defense and any related settlement +negotiations. The Indemnified Contributor may participate in any such +claim at its own expense. + +For example, a Contributor might include the Program in a commercial +product offering, Product X. That Contributor is then a Commercial +Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance +claims and warranties are such Commercial Contributor's responsibility +alone. Under this section, the Commercial Contributor would have to +defend claims against the other Contributors related to those +performance claims and warranties, and if a court requires any other +Contributor to pay any damages as a result, the Commercial Contributor +must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS +PROVIDED 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. Each Recipient is solely +responsible for determining the appropriateness of using and +distributing the Program and assumes all risks associated with its +exercise of rights under this Agreement , including but not limited to +the risks and costs of program errors, compliance with applicable +laws, damage to or loss of data, programs or equipment, and +unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR +ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR +DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED +HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of +the remainder of the terms of this Agreement, and without further +action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity +(including a cross-claim or counterclaim in a lawsuit) alleging that +the Program itself (excluding combinations of the Program with other +software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of +the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it +fails to comply with any of the material terms or conditions of this +Agreement and does not cure such failure in a reasonable period of +time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use +and distribution of the Program as soon as reasonably practicable. +However, Recipient's obligations under this Agreement and any licenses +granted by Recipient relating to the Program shall continue and +survive. + +Everyone is permitted to copy and distribute copies of this Agreement, +but in order to avoid inconsistency the Agreement is copyrighted and +may only be modified in the following manner. The Agreement Steward +reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement +Steward has the right to modify this Agreement. The Eclipse Foundation +is the initial Agreement Steward. The Eclipse Foundation may assign +the responsibility to serve as the Agreement Steward to a suitable +separate entity. Each new version of the Agreement will be given a +distinguishing version number. The Program (including Contributions) +may always be distributed subject to the version of the Agreement +under which it was received. In addition, after a new version of the +Agreement is published, Contributor may elect to distribute the +Program (including its Contributions) under the new version. Except as +expressly stated in Sections 2(a) and 2(b) above, Recipient receives +no rights or licenses to the intellectual property of any Contributor +under this Agreement, whether expressly, by implication, estoppel or +otherwise. All rights in the Program not expressly granted under this +Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and +the intellectual property laws of the United States of America. No +party to this Agreement will bring a legal action under this Agreement +more than one year after the cause of action arose. Each party waives +its rights to a jury trial in any resulting litigation. + +=============================================================================== + +For the Rhino JavaScript container component: + +Mozilla Public License 1.1 (MPL 1.1) + +1. Definitions. + + 1.0.1. "Commercial Use" means distribution or otherwise making the +Covered Code available to a third party. + + 1.1. "Contributor" means each entity that creates or contributes to +the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the Original Code, +prior Modifications used by a Contributor, and the Modifications made by that +particular Contributor. + + 1.3. "Covered Code" means the Original Code or Modifications or the +combination of the Original Code and Modifications, in each case including +portions thereof. + + 1.4. "Electronic Distribution Mechanism" means a mechanism generally +accepted in the software development community for the electronic transfer of +data. + + 1.5. "Executable" means Covered Code in any form other than Source +Code. + + 1.6. "Initial Developer" means the individual or entity identified as +the Initial Developer in the Source Code notice required by Exhibit A. + + 1.7. "Larger Work" means a work which combines Covered Code or +portions thereof with code not governed by the terms of this License. + + 1.8. "License" means this document. + + 1.8.1. "Licensable" means having the right to grant, to the maximum +extent possible, whether at the time of the initial grant or subsequently +acquired, any and all of the rights conveyed herein. + + 1.9. "Modifications" means any addition to or deletion from the +substance or structure of either the Original Code or any previous +Modifications. When Covered Code is released as a series of files, a +Modification is: + A. Any addition to or deletion from the contents of a file +containing Original Code or previous Modifications. + + B. Any new file that contains any part of the Original Code or +previous Modifications. + + 1.10. "Original Code" means Source Code of computer software code +which is described in the Source Code notice required by Exhibit A as Original +Code, and which, at the time of its release under this License is not already +Covered Code governed by this License. + + 1.10.1. "Patent Claims" means any patent claim(s), now owned or +hereafter acquired, including without limitation, method, process, and +apparatus claims, in any patent Licensable by grantor. + + 1.11. "Source Code" means the preferred form of the Covered Code for +making modifications to it, including all modules it contains, plus any +associated interface definition files, scripts used to control compilation and +installation of an Executable, or source code differential comparisons against +either the Original Code or another well known, available Covered Code of the +Contributor's choice. The Source Code can be in a compressed or archival form, +provided the appropriate decompression or de-archiving software is widely +available for no charge. + + 1.12. "You" (or "Your") means an individual or a legal entity +exercising rights under, and complying with all of the terms of, this License +or a future version of this License issued under Section 6.1. For legal +entities, "You" includes any entity which controls, is controlled by, or is +under common control with You. For purposes of this definition, "control" +means (a) the power, direct or indirect, to cause the direction or management +of such entity, whether by contract or otherwise, or (b) ownership of more +than fifty percent (50%) of the outstanding shares or beneficial ownership of +such entity. + +2. Source Code License. + + 2.1. The Initial Developer Grant. + The Initial Developer hereby grants You a world-wide, royalty-free, +non-exclusive license, subject to third party intellectual property claims: + (a) under intellectual property rights (other than patent or +trademark) Licensable by Initial Developer to use, reproduce, modify, display, +perform, sublicense and distribute the Original Code (or portions thereof) +with or without Modifications, and/or as part of a Larger Work; and + + (b) under Patents Claims infringed by the making, using or selling +of Original Code, to make, have made, use, practice, sell, and offer for sale, +and/or otherwise dispose of the Original Code (or portions thereof). + (c) the licenses granted in this Section 2.1(a) and +(b) are effective on the date Initial Developer first distributes Original +Code under the terms of this License. + + (d) Notwithstanding Section 2.1(b) above, no patent license is +granted: 1) for code that You delete from the Original Code; 2) separate from +the Original Code; or 3) for infringements caused by: i) the modification of +the Original Code or ii) the combination of the Original Code with other +software or devices. + + 2.2. Contributor Grant. + Subject to third party intellectual property claims, each Contributor +hereby grants You a world-wide, royalty-free, non-exclusive license + + (a) under intellectual property rights (other than patent or +trademark) Licensable by Contributor, to use, reproduce, modify, display, +perform, sublicense and distribute the Modifications created by such +Contributor (or portions thereof) either on an unmodified basis, with other +Modifications, as Covered Code and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using, or selling +of Modifications made by that Contributor either alone and/or in combination +with its Contributor Version (or portions of such combination), to make, use, +sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications +made by that Contributor (or portions thereof); and 2) the combination of +Modifications made by that Contributor with its Contributor Version (or +portions of such combination). + + (c) the licenses granted in Sections 2.2(a) and 2.2(b) are +effective on the date Contributor first makes Commercial Use of the Covered +Code. + + (d) Notwithstanding Section 2.2(b) above, no patent license is +granted: 1) for any code that Contributor has deleted from the Contributor +Version; 2) separate from the Contributor Version; 3) for infringements +caused by: i) third party modifications of Contributor Version or ii) the +combination of Modifications made by that Contributor with other software +(except as part of the Contributor Version) or other devices; or 4) under +Patent Claims infringed by Covered Code in the absence of Modifications made +by that Contributor. + + +3. Distribution Obligations. + + 3.1. Application of License. + The Modifications which You create or to which You contribute are +governed by the terms of this License, including without limitation Section +2.2. The Source Code version of Covered Code may be distributed only under the +terms of this License or a future version of this License released under +Section 6.1, and You must include a copy of this License with every copy of +the Source Code You distribute. You may not offer or impose any terms on any +Source Code version that alters or restricts the applicable version of this +License or the recipients' rights hereunder. However, You may include an +additional document offering the additional rights described in Section 3.5. + + 3.2. Availability of Source Code. + Any Modification which You create or to which You contribute must be +made available in Source Code form under the terms of this License either on +the same media as an Executable version or via an accepted Electronic +Distribution Mechanism to anyone to whom you made an Executable version +available; and if made available via Electronic Distribution Mechanism, must +remain available for at least twelve (12) months after the date it initially +became available, or at least six (6) months after a subsequent version of +that particular Modification has been made available to such recipients. You +are responsible for ensuring that the Source Code version remains available +even if the Electronic Distribution Mechanism is maintained by a third party. + + 3.3. Description of Modifications. + You must cause all Covered Code to which You contribute to contain a +file documenting the changes You made to create that Covered Code and the date +of any change. You must include a prominent statement that the Modification is +derived, directly or indirectly, from Original Code provided by the Initial +Developer and including the name of the Initial Developer in (a) the Source +Code, and (b) in any notice in an Executable version or related documentation +in which You describe the origin or ownership of the Covered Code. + + 3.4. Intellectual Property Matters + (a) Third Party Claims. + If Contributor has knowledge that a license under a third party's +intellectual property rights is required to exercise the rights granted by +such Contributor under Sections 2.1 or 2.2, Contributor must include a text +file with the Source Code distribution titled "LEGAL" which describes the +claim and the party making the claim in sufficient detail that a recipient +will know whom to contact. If Contributor obtains such knowledge after the +Modification is made available as described in Section 3.2, Contributor shall +promptly modify the LEGAL file in all copies Contributor makes available +thereafter and shall take other steps (such as notifying appropriate mailing +lists or newsgroups) reasonably calculated to inform those who received the +Covered Code that new knowledge has been obtained. + + (b) Contributor APIs. + If Contributor's Modifications include an application programming +interface and Contributor has knowledge of patent licenses which are +reasonably necessary to implement that API, Contributor must also include this +information in the LEGAL file. + + (c) Representations. + Contributor represents that, except as disclosed pursuant to +Section 3.4(a) above, Contributor believes that Contributor's Modifications +are Contributor's original creation(s) and/or Contributor has sufficient +rights to grant the rights conveyed by this License. + + + 3.5. Required Notices. + You must duplicate the notice in Exhibit A in each file of the Source +Code. If it is not possible to put such notice in a particular Source Code +file due to its structure, then You must include such notice in a location +(such as a relevant directory) where a user would be likely to look for such a +notice. If You created one or more Modification(s) You may add your name as a +Contributor to the notice described in Exhibit A. You must also duplicate +this License in any documentation for the Source Code where You describe +recipients' rights or ownership rights relating to Covered Code. You may +choose to offer, and to charge a fee for, warranty, support, indemnity or +liability obligations to one or more recipients of Covered Code. However, You +may do so only on Your own behalf, and not on behalf of the Initial Developer +or any Contributor. You must make it absolutely clear than any such warranty, +support, indemnity or liability obligation is offered by You alone, and You +hereby agree to indemnify the Initial Developer and every Contributor for any +liability incurred by the Initial Developer or such Contributor as a result of +warranty, support, indemnity or liability terms You offer. + + 3.6. Distribution of Executable Versions. + You may distribute Covered Code in Executable form only if the +requirements of Section 3.1-3.5 have been met for that Covered Code, and if +You include a notice stating that the Source Code version of the Covered Code +is available under the terms of this License, including a description of how +and where You have fulfilled the obligations of Section 3.2. The notice must +be conspicuously included in any notice in an Executable version, related +documentation or collateral in which You describe recipients' rights relating +to the Covered Code. You may distribute the Executable version of Covered Code +or ownership rights under a license of Your choice, which may contain terms +different from this License, provided that You are in compliance with the +terms of this License and that the license for the Executable version does not +attempt to limit or alter the recipient's rights in the Source Code version +from the rights set forth in this License. If You distribute the Executable +version under a different license You must make it absolutely clear that any +terms which differ from this License are offered by You alone, not by the +Initial Developer or any Contributor. You hereby agree to indemnify the +Initial Developer and every Contributor for any liability incurred by the +Initial Developer or such Contributor as a result of any such terms You offer. + + 3.7. Larger Works. + You may create a Larger Work by combining Covered Code with other code +not governed by the terms of this License and distribute the Larger Work as a +single product. In such a case, You must make sure the requirements of this +License are fulfilled for the Covered Code. + +4. Inability to Comply Due to Statute or Regulation. + + If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Code due to statute, +judicial order, or regulation then You must: (a) comply with the terms of this +License to the maximum extent possible; and (b) describe the limitations and +the code they affect. Such description must be included in the LEGAL file +described in Section 3.4 and must be included with all distributions of the +Source Code. Except to the extent prohibited by statute or regulation, such +description must be sufficiently detailed for a recipient of ordinary skill to +be able to understand it. + +5. Application of this License. + + This License applies to code to which the Initial Developer has attached +the notice in Exhibit A and to related Covered Code. + +6. Versions of the License. + + 6.1. New Versions. + Netscape Communications Corporation ("Netscape") may publish revised +and/or new versions of the License from time to time. Each version will be +given a distinguishing version number. + + 6.2. Effect of New Versions. + Once Covered Code has been published under a particular version of the +License, You may always continue to use it under the terms of that version. +You may also choose to use such Covered Code under the terms of any subsequent +version of the License published by Netscape. No one other than Netscape has +the right to modify the terms applicable to Covered Code created under this +License. + + 6.3. Derivative Works. + If You create or use a modified version of this License (which you may +only do in order to apply it to code which is not already Covered Code +governed by this License), You must (a) rename Your license so that the +phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", "MPL", "NPL" or +any confusingly similar phrase do not appear in your license (except to note +that your license differs from this License) and (b) otherwise make it clear +that Your version of the license contains terms which differ from the Mozilla +Public License and Netscape Public License. (Filling in the name of the +Initial Developer, Original Code or Contributor in the notice described in +Exhibit A shall not of themselves be deemed to be modifications of this +License.) + +7. DISCLAIMER OF WARRANTY. + + COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, +WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT +LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, +FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE +QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED +CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY +OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR +CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS +LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS +DISCLAIMER. + +8. TERMINATION. + + 8.1. This License and the rights granted hereunder will terminate +automatically if You fail to comply with terms herein and fail to cure such +breach within 30 days of becoming aware of the breach. All sublicenses to the +Covered Code which are properly granted shall survive any termination of this +License. Provisions which, by their nature, must remain in effect beyond the +termination of this License shall survive. + + 8.2. If You initiate litigation by asserting a patent infringement +claim (excluding declatory judgment actions) against Initial Developer or a +Contributor (the Initial Developer or Contributor against whom You file such +action is referred to as "Participant") alleging that: + + (a) such Participant's Contributor Version directly or indirectly +infringes any patent, then any and all rights granted by such Participant to +You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice +from Participant terminate prospectively, unless if within 60 days after +receipt of notice You either: (i) agree in writing to pay Participant a +mutually agreeable reasonable royalty for Your past and future use of +Modifications made by such Participant, or (ii) withdraw Your litigation claim +with respect to the Contributor Version against such Participant. If within +60 days of notice, a reasonable royalty and payment arrangement are not +mutually agreed upon in writing by the parties or the litigation claim is not +withdrawn, the rights granted by Participant to You under Sections 2.1 and/or +2.2 automatically terminate at the expiration of the 60 day notice period +specified above. + + (b) any software, hardware, or device, other than such Participant's +Contributor Version, directly or indirectly infringes any patent, then any +rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are +revoked effective as of the date You first made, used, sold, distributed, or +had made, Modifications made by that Participant. + + 8.3. If You assert a patent infringement claim against Participant +alleging that such Participant's Contributor Version directly or indirectly +infringes any patent where such claim is resolved (such as by license or +settlement) prior to the initiation of patent infringement litigation, then +the reasonable value of the licenses granted by such Participant under +Sections 2.1 or 2.2 shall be taken into account in determining the amount or +value of any payment or license. + + 8.4. In the event of termination under Sections 8.1 or 8.2 above, all +end user license agreements (excluding distributors and resellers) which have +been validly granted by You or any distributor hereunder prior to termination +shall survive termination. + +9. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT +(INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL +DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY +SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, +SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, +WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER +FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, +EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH +DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH +OR PERSONAL INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT +APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE +EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS +EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + +10. U.S. GOVERNMENT END USERS. + + The Covered Code is a "commercial item," as that term is defined in 48 +C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer software" and +"commercial computer software documentation," as such terms are used in 48 +C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. +227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users +acquire Covered Code with only those rights set forth herein. + +11. MISCELLANEOUS. + + This License represents the complete agreement concerning subject matter +hereof. If any provision of this License is held to be unenforceable, such +provision shall be reformed only to the extent necessary to make it +enforceable. This License shall be governed by California law provisions +(except to the extent applicable law, if any, provides otherwise), excluding +its conflict-of-law provisions. With respect to disputes in which at least one +party is a citizen of, or an entity chartered or registered to do business in +the United States of America, any litigation relating to this License shall be +subject to the jurisdiction of the Federal Courts of the Northern District of +California, with venue lying in Santa Clara County, California, with the +losing party responsible for costs, including without limitation, court costs +and reasonable attorneys' fees and expenses. The application of the United +Nations Convention on Contracts for the International Sale of Goods is +expressly excluded. Any law or regulation which provides that the language of +a contract shall be construed against the drafter shall not apply to this +License. + +12. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is +responsible for claims and damages arising, directly or indirectly, out of its +utilization of rights under this License and You agree to work with Initial +Developer and Contributors to distribute such responsibility on an equitable +basis. Nothing herein is intended or shall be deemed to constitute any +admission of liability. + +13. MULTIPLE-LICENSED CODE. + + Initial Developer may designate portions of the Covered Code as +Multiple-Licensed. Multiple-Licensed means that the Initial Developer permits +you to utilize portions of the Covered Code under Your choice of the MPL or +the alternative licenses, if any, specified by the Initial Developer in the +file described in Exhibit A. + + +EXHIBIT A -Mozilla Public License. + + ``The contents of this file are subject to the Mozilla Public License +Version 1.1 (the "License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + http://www.mozilla.org/MPL/ + + Software distributed under the License is distributed on an "AS IS" +basis, WITHOUT WARRANTY OF + ANY KIND, either express or implied. See the License for the specific +language governing rights and + limitations under the License. + + The Original Code is ______________________________________. + + The Initial Developer of the Original Code is ________________________. +Portions created by + ______________________ are Copyright (C) ______ +_______________________. All Rights + Reserved. + + Contributor(s): ______________________________________. + + Alternatively, the contents of this file may be used under the terms of +the _____ license (the [___] License), in which case the provisions of +[______] License are applicable instead of those above. If you wish to allow +use of your version of this file only under the terms of the [____] License +and not to allow others to use your version of this file under the MPL, +indicate your decision by deleting the provisions above and replace them +with the notice and other provisions required by the [___] License. If you do +not delete the provisions above, a recipient may use your version of this file +under either the MPL or the [___] License." + + [NOTE: The text of this Exhibit A may differ slightly from the text of +the notices in the Source Code files of the Original Code. You should use the +text of this Exhibit A rather than the text found in the Original Code Source +Code for Your Modifications.] + + +=============================================================================== + +For the JAX-WS Reference Implementation component: + +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 + + + 1. Definitions. + + 1.1. "Contributor" means each individual or entity that + creates or contributes to the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the + Original Software, prior Modifications used by a + Contributor (if any), and the Modifications made by that + particular Contributor. + + 1.3. "Covered Software" means (a) the Original Software, or + (b) Modifications, or (c) the combination of files + containing Original Software with files containing + Modifications, in each case including portions thereof. + + 1.4. "Executable" means the Covered Software in any form + other than Source Code. + + 1.5. "Initial Developer" means the individual or entity + that first makes Original Software available under this + License. + + 1.6. "Larger Work" means a work which combines Covered + Software or portions thereof with code not governed by the + terms of this License. + + 1.7. "License" means this document. + + 1.8. "Licensable" means having the right to grant, to the + maximum extent possible, whether at the time of the initial + grant or subsequently acquired, any and all of the rights + conveyed herein. + + 1.9. "Modifications" means the Source Code and Executable + form of any of the following: + + A. Any file that results from an addition to, + deletion from or modification of the contents of a + file containing Original Software or previous + Modifications; + + B. Any new file that contains any part of the + Original Software or previous Modification; or + + C. Any new file that is contributed or otherwise made + available under the terms of this License. + + 1.10. "Original Software" means the Source Code and + Executable form of computer software code that is + originally released under this License. + + 1.11. "Patent Claims" means any patent claim(s), now owned + or hereafter acquired, including without limitation, + method, process, and apparatus claims, in any patent + Licensable by grantor. + + 1.12. "Source Code" means (a) the common form of computer + software code in which modifications are made and (b) + associated documentation included in or with such code. + + 1.13. "You" (or "Your") means an individual or a legal + entity exercising rights under, and complying with all of + the terms of, this License. For legal entities, "You" + includes any entity which controls, is controlled by, or is + under common control with You. For purposes of this + definition, "control" means (a) the power, direct or + indirect, to cause the direction or management of such + entity, whether by contract or otherwise, or (b) ownership + of more than fifty percent (50%) of the outstanding shares + or beneficial ownership of such entity. + + 2. License Grants. + + 2.1. The Initial Developer Grant. + + Conditioned upon Your compliance with Section 3.1 below and + subject to third party intellectual property claims, the + Initial Developer hereby grants You a world-wide, + royalty-free, non-exclusive license: + + (a) under intellectual property rights (other than + patent or trademark) Licensable by Initial Developer, + to use, reproduce, modify, display, perform, + sublicense and distribute the Original Software (or + portions thereof), with or without Modifications, + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, + using or selling of Original Software, to make, have + made, use, practice, sell, and offer for sale, and/or + otherwise dispose of the Original Software (or + portions thereof). + + (c) The licenses granted in Sections 2.1(a) and (b) + are effective on the date Initial Developer first + distributes or otherwise makes the Original Software + available to a third party under the terms of this + License. + + (d) Notwithstanding Section 2.1(b) above, no patent + license is granted: (1) for code that You delete from + the Original Software, or (2) for infringements + caused by: (i) the modification of the Original + Software, or (ii) the combination of the Original + Software with other software or devices. + + 2.2. Contributor Grant. + + Conditioned upon Your compliance with Section 3.1 below and + subject to third party intellectual property claims, each + Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + (a) under intellectual property rights (other than + patent or trademark) Licensable by Contributor to + use, reproduce, modify, display, perform, sublicense + and distribute the Modifications created by such + Contributor (or portions thereof), either on an + unmodified basis, with other Modifications, as + Covered Software and/or as part of a Larger Work; and + + + (b) under Patent Claims infringed by the making, + using, or selling of Modifications made by that + Contributor either alone and/or in combination with + its Contributor Version (or portions of such + combination), to make, use, sell, offer for sale, + have made, and/or otherwise dispose of: (1) + Modifications made by that Contributor (or portions + thereof); and (2) the combination of Modifications + made by that Contributor with its Contributor Version + (or portions of such combination). + + (c) The licenses granted in Sections 2.2(a) and + 2.2(b) are effective on the date Contributor first + distributes or otherwise makes the Modifications + available to a third party. + + (d) Notwithstanding Section 2.2(b) above, no patent + license is granted: (1) for any code that Contributor + has deleted from the Contributor Version; (2) for + infringements caused by: (i) third party + modifications of Contributor Version, or (ii) the + combination of Modifications made by that Contributor + with other software (except as part of the + Contributor Version) or other devices; or (3) under + Patent Claims infringed by Covered Software in the + absence of Modifications made by that Contributor. + + 3. Distribution Obligations. + + 3.1. Availability of Source Code. + + Any Covered Software that You distribute or otherwise make + available in Executable form must also be made available in + Source Code form and that Source Code form must be + distributed only under the terms of this License. You must + include a copy of this License with every copy of the + Source Code form of the Covered Software You distribute or + otherwise make available. You must inform recipients of any + such Covered Software in Executable form as to how they can + obtain such Covered Software in Source Code form in a + reasonable manner on or through a medium customarily used + for software exchange. + + 3.2. Modifications. + + The Modifications that You create or to which You + contribute are governed by the terms of this License. You + represent that You believe Your Modifications are Your + original creation(s) and/or You have sufficient rights to + grant the rights conveyed by this License. + + 3.3. Required Notices. + + You must include a notice in each of Your Modifications + that identifies You as the Contributor of the Modification. + You may not remove or alter any copyright, patent or + trademark notices contained within the Covered Software, or + any notices of licensing or any descriptive text giving + attribution to any Contributor or the Initial Developer. + + 3.4. Application of Additional Terms. + + You may not offer or impose any terms on any Covered + Software in Source Code form that alters or restricts the + applicable version of this License or the recipients' + rights hereunder. You may choose to offer, and to charge a + fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Software. + However, you may do so only on Your own behalf, and not on + behalf of the Initial Developer or any Contributor. You + must make it absolutely clear that any such warranty, + support, indemnity or liability obligation is offered by + You alone, and You hereby agree to indemnify the Initial + Developer and every Contributor for any liability incurred + by the Initial Developer or such Contributor as a result of + warranty, support, indemnity or liability terms You offer. + + + 3.5. Distribution of Executable Versions. + + You may distribute the Executable form of the Covered + Software under the terms of this License or under the terms + of a license of Your choice, which may contain terms + different from this License, provided that You are in + compliance with the terms of this License and that the + license for the Executable form does not attempt to limit + or alter the recipient's rights in the Source Code form + from the rights set forth in this License. If You + distribute the Covered Software in Executable form under a + different license, You must make it absolutely clear that + any terms which differ from this License are offered by You + alone, not by the Initial Developer or Contributor. You + hereby agree to indemnify the Initial Developer and every + Contributor for any liability incurred by the Initial + Developer or such Contributor as a result of any such terms + You offer. + + 3.6. Larger Works. + + You may create a Larger Work by combining Covered Software + with other code not governed by the terms of this License + and distribute the Larger Work as a single product. In such + a case, You must make sure the requirements of this License + are fulfilled for the Covered Software. + + 4. Versions of the License. + + 4.1. New Versions. + + Sun Microsystems, Inc. is the initial license steward and + may publish revised and/or new versions of this License + from time to time. Each version will be given a + distinguishing version number. Except as provided in + Section 4.3, no one other than the license steward has the + right to modify this License. + + 4.2. Effect of New Versions. + + You may always continue to use, distribute or otherwise + make the Covered Software available under the terms of the + version of the License under which You originally received + the Covered Software. If the Initial Developer includes a + notice in the Original Software prohibiting it from being + distributed or otherwise made available under any + subsequent version of the License, You must distribute and + make the Covered Software available under the terms of the + version of the License under which You originally received + the Covered Software. Otherwise, You may also choose to + use, distribute or otherwise make the Covered Software + available under the terms of any subsequent version of the + License published by the license steward. + + 4.3. Modified Versions. + + When You are an Initial Developer and You want to create a + new license for Your Original Software, You may create and + use a modified version of this License if You: (a) rename + the license and remove any references to the name of the + license steward (except to note that the license differs + from this License); and (b) otherwise make it clear that + the license contains terms which differ from this License. + + + 5. DISCLAIMER OF WARRANTY. + + COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" + BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, + INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED + SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR + PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND + PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY + COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE + INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF + ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF + WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF + ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS + DISCLAIMER. + + 6. TERMINATION. + + 6.1. This License and the rights granted hereunder will + terminate automatically if You fail to comply with terms + herein and fail to cure such breach within 30 days of + becoming aware of the breach. Provisions which, by their + nature, must remain in effect beyond the termination of + this License shall survive. + + 6.2. If You assert a patent infringement claim (excluding + declaratory judgment actions) against Initial Developer or + a Contributor (the Initial Developer or Contributor against + whom You assert such claim is referred to as "Participant") + alleging that the Participant Software (meaning the + Contributor Version where the Participant is a Contributor + or the Original Software where the Participant is the + Initial Developer) directly or indirectly infringes any + patent, then any and all rights granted directly or + indirectly to You by such Participant, the Initial + Developer (if the Initial Developer is not the Participant) + and all Contributors under Sections 2.1 and/or 2.2 of this + License shall, upon 60 days notice from Participant + terminate prospectively and automatically at the expiration + of such 60 day notice period, unless if within such 60 day + period You withdraw Your claim with respect to the + Participant Software against such Participant either + unilaterally or pursuant to a written agreement with + Participant. + + 6.3. In the event of termination under Sections 6.1 or 6.2 + above, all end user licenses that have been validly granted + by You or any distributor hereunder prior to termination + (excluding licenses granted to You by any distributor) + shall survive termination. + + 7. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE + INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF + COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE + LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT + LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK + STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER + COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN + INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF + LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL + INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT + APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO + NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR + CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT + APPLY TO YOU. + + 8. U.S. GOVERNMENT END USERS. + + The Covered Software is a "commercial item," as that term is + defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial + computer software" (as that term is defined at 48 C.F.R. + 252.227-7014(a)(1)) and "commercial computer software + documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. + 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 + through 227.7202-4 (June 1995), all U.S. Government End Users + acquire Covered Software with only those rights set forth herein. + This U.S. Government Rights clause is in lieu of, and supersedes, + any other FAR, DFAR, or other clause or provision that addresses + Government rights in computer software under this License. + + 9. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the + extent necessary to make it enforceable. This License shall be + governed by the law of the jurisdiction specified in a notice + contained within the Original Software (except to the extent + applicable law, if any, provides otherwise), excluding such + jurisdiction's conflict-of-law provisions. Any litigation + relating to this License shall be subject to the jurisdiction of + the courts located in the jurisdiction and venue specified in a + notice contained within the Original Software, with the losing + party responsible for costs, including, without limitation, court + costs and reasonable attorneys' fees and expenses. The + application of the United Nations Convention on Contracts for the + International Sale of Goods is expressly excluded. Any law or + regulation which provides that the language of a contract shall + be construed against the drafter shall not apply to this License. + You agree that You alone are responsible for compliance with the + United States export administration regulations (and the export + control laws and regulation of any other countries) when You use, + distribute or otherwise make available any Covered Software. + + 10. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or + indirectly, out of its utilization of rights under this License + and You agree to work with Initial Developer and Contributors to + distribute such responsibility on an equitable basis. Nothing + herein is intended or shall be deemed to constitute any admission + of liability. + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/NOTICE b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/NOTICE new file mode 100644 index 0000000000..d48810c0ec --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/NOTICE @@ -0,0 +1,18 @@ +========================================================================= +== NOTICE file corresponding to the section 4 d of == +== the Apache License, Version 2.0, == +== in this case for the Apache Tuscany distribution. == +========================================================================= + +This product includes software developed by the Apache Software Foundation +(http://www.apache.org/). + +This product also includes software developed by: +- the Eclipse Modeling Framework project (http://www.eclipse.org/emf/) +- the Celtix project (http://celtix.objectweb.org/) +- the Mozilla Rhino project (http://www.mozilla.org/rhino/) +- the GlassFish JAX-WS project (https://jax-ws.dev.java.net/) + +Please read the LICENSE.txt file present in the root directory of this +distribution. + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..5bb55f2405 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.rmi/src/test/resources/META-INF/sca/default.scdl @@ -0,0 +1,44 @@ +<?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. + --> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:rmi="http://incubator.apache.org/tuscany/xmlns/binding/rmi/1.0-incubator-M2" + name="HelloWorldRmiComposite"> + + <service name="HelloWorldRmiService" target="HelloWorldServiceComponent"> + <interface.java interface="helloworld.HelloWorldService"/> + <rmi:binding.rmi host="localhost" port="8099" serviceName="HelloWorldRemoteService" /> + <reference>HelloWorldServiceComponent</reference> + </service> + + <component name="HelloWorldServiceComponent"> + <implementation.java class="helloworld.HelloWorldImpl"/> + </component> + + <component name="HelloWorldRmiServiceComponent"> + <implementation.java class="helloworld.HelloWorldRmiImpl"/> + <reference name="extService" target="HelloWorldRmiReference">HelloWorldRmiReference</reference> + </component> + + <reference name="HelloWorldRmiReference" target="Nothing"> + <interface.java interface="helloworld.HelloWorldService"/> + <rmi:binding.rmi host="localhost" port="8099" serviceName="HelloWorldRemoteService" /> + </reference> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/pom.xml new file mode 100644 index 0000000000..fcb4b086c4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/pom.xml @@ -0,0 +1,60 @@ +<?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 xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <parent> + <groupId>org.apache.tuscany.sca.services.bindings</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>binding-servicemix</artifactId> + <name>Apache Tuscany Binding for ServiceMix</name> + <description>Implementation of the SCA JBI Binding</description> + + <dependencies> + + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.servicemix</groupId> + <artifactId>servicemix-core</artifactId> + <version>3.0-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.servicemix</groupId> + <artifactId>servicemix-common</artifactId> + <version>3.0-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + + </dependencies> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaBootstrap.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaBootstrap.java new file mode 100644 index 0000000000..ad407553b4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaBootstrap.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.jbi.JBIException; +import javax.jbi.component.Bootstrap; +import javax.jbi.component.InstallationContext; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +/** + * Base class for components bootstrap. + * + * @author Guillaume Nodet + * @version $Revision$ + * @since 3.0 + */ +public class ScaBootstrap implements Bootstrap { + + protected final transient Log logger = LogFactory.getLog(getClass()); + + protected InstallationContext context; + protected ObjectName mbeanName; + + public ScaBootstrap() { + } + + public ObjectName getExtensionMBeanName() { + return mbeanName; + } + + protected Object getExtensionMBean() throws Exception { + return null; + } + + protected ObjectName createExtensionMBeanName() throws Exception { + return this.context.getContext().getMBeanNames().createCustomComponentMBeanName("bootstrap"); + } + + /* (non-Javadoc) + * @see javax.jbi.component.Bootstrap#init(javax.jbi.component.InstallationContext) + */ + public void init(InstallationContext installContext) throws JBIException { + try { + if (logger.isDebugEnabled()) { + logger.debug("Initializing bootstrap"); + } + this.context = installContext; + doInit(); + if (logger.isDebugEnabled()) { + logger.debug("Bootstrap initialized"); + } + } catch (JBIException e) { + throw e; + } catch (Exception e) { + throw new JBIException("Error calling init", e); + } + } + + protected void doInit() throws Exception { + Object mbean = getExtensionMBean(); + if (mbean != null) { + this.mbeanName = createExtensionMBeanName(); + MBeanServer server = this.context.getContext().getMBeanServer(); + if (server == null) { + throw new JBIException("null mBeanServer"); + } + if (server.isRegistered(this.mbeanName)) { + server.unregisterMBean(this.mbeanName); + } + server.registerMBean(mbean, this.mbeanName); + } + } + + /* (non-Javadoc) + * @see javax.jbi.component.Bootstrap#cleanUp() + */ + public void cleanUp() throws JBIException { + try { + if (logger.isDebugEnabled()) { + logger.debug("Cleaning up bootstrap"); + } + doCleanUp(); + if (logger.isDebugEnabled()) { + logger.debug("Bootstrap cleaned up"); + } + } catch (JBIException e) { + throw e; + } catch (Exception e) { + throw new JBIException("Error calling cleanUp", e); + } + } + + protected void doCleanUp() throws Exception { + if (this.mbeanName != null) { + MBeanServer server = this.context.getContext().getMBeanServer(); + if (server == null) { + throw new JBIException("null mBeanServer"); + } + if (server.isRegistered(this.mbeanName)) { + server.unregisterMBean(this.mbeanName); + } + } + } + + /* (non-Javadoc) + * @see javax.jbi.component.Bootstrap#onInstall() + */ + public void onInstall() throws JBIException { + try { + if (logger.isDebugEnabled()) { + logger.debug("Bootstrap onInstall"); + } + doOnInstall(); + if (logger.isDebugEnabled()) { + logger.debug("Bootstrap onInstall done"); + } + } catch (JBIException e) { + throw e; + } catch (Exception e) { + throw new JBIException("Error calling onInstall", e); + } + } + + protected void doOnInstall() throws Exception { + } + + /* (non-Javadoc) + * @see javax.jbi.component.Bootstrap#onUninstall() + */ + public void onUninstall() throws JBIException { + try { + if (logger.isDebugEnabled()) { + logger.debug("Bootstrap onUninstall"); + } + doOnUninstall(); + if (logger.isDebugEnabled()) { + logger.debug("Bootstrap onUninstall done"); + } + } catch (JBIException e) { + throw e; + } catch (Exception e) { + throw new JBIException("Error calling onUninstall", e); + } + } + + protected void doOnUninstall() throws Exception { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaComponent.java new file mode 100644 index 0000000000..93470e0707 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaComponent.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.servicemix.sca; + +import org.apache.servicemix.common.BaseComponent; +import org.apache.servicemix.common.BaseLifeCycle; +import org.apache.servicemix.common.BaseServiceUnitManager; +import org.apache.servicemix.common.Deployer; + +public class ScaComponent extends BaseComponent { + + /* (non-Javadoc) + * @see org.servicemix.common.BaseComponent#createLifeCycle() + */ + protected BaseLifeCycle createLifeCycle() { + return new ScaLifeCycle(this); + } + + /* (non-Javadoc) + * @see org.servicemix.common.BaseComponent#createServiceUnitManager() + */ + public BaseServiceUnitManager createServiceUnitManager() { + Deployer[] deployers = new Deployer[] { new ScaDeployer(this) }; + return new BaseServiceUnitManager(this, deployers); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaDeployer.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaDeployer.java new file mode 100644 index 0000000000..199721cb88 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaDeployer.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.servicemix.sca; + +import java.io.File; + +import javax.jbi.management.DeploymentException; + +import org.apache.servicemix.common.AbstractDeployer; +import org.apache.servicemix.common.BaseComponent; +import org.apache.servicemix.common.ServiceUnit; + +public class ScaDeployer extends AbstractDeployer { + + public static final String SCA_MODULE_FILE = "sca.module"; + + public ScaDeployer(BaseComponent component) { + super(component); + } + + public boolean canDeploy(String serviceUnitName, String serviceUnitRootPath) { + File module = new File(serviceUnitRootPath, SCA_MODULE_FILE); + return module.exists() && module.isFile(); + } + + public ServiceUnit deploy(String serviceUnitName, String serviceUnitRootPath) + throws DeploymentException { + File module = new File(serviceUnitRootPath, SCA_MODULE_FILE); + if (!module.exists() || !module.isFile()) { + throw failure("deploy", "No sca.module found", null); + } + try { + ScaServiceUnit su = new ScaServiceUnit(); + su.setComponent(component); + su.setName(serviceUnitName); + su.setRootPath(serviceUnitRootPath); + su.init(); + return su; + } catch (Exception e) { + throw failure("deploy", "Error loading sca module", e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaEndpoint.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaEndpoint.java new file mode 100644 index 0000000000..8da798d26f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaEndpoint.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca; + +import java.io.StringWriter; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.UndeclaredThrowableException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.jbi.component.ComponentContext; +import javax.jbi.messaging.DeliveryChannel; +import javax.jbi.messaging.ExchangeStatus; +import javax.jbi.messaging.MessageExchange; +import javax.jbi.messaging.NormalizedMessage; +import javax.jbi.messaging.MessageExchange.Role; +import javax.jbi.servicedesc.ServiceEndpoint; +import javax.xml.bind.JAXBContext; + +import org.apache.servicemix.common.Endpoint; +import org.apache.servicemix.common.ExchangeProcessor; +import org.apache.servicemix.jbi.jaxp.StringSource; +import org.apache.tuscany.core.context.EntryPointContext; +import org.apache.tuscany.model.assembly.ConfiguredReference; +import org.apache.tuscany.model.assembly.ConfiguredService; +import org.apache.tuscany.model.assembly.EntryPoint; + +/** + * + * @author gnodet + * @version $Revision$ + * @org.apache.xbean.XBean element="endpoint" description="A sca endpoint" + * + */ +public class ScaEndpoint extends Endpoint implements ExchangeProcessor { + + protected ServiceEndpoint activated; + + protected EntryPoint entryPoint; + + protected Map<Class, Method> methodMap; + + protected JAXBContext jaxbContext; + + protected DeliveryChannel channel; + + public ScaEndpoint(EntryPoint entryPoint) { + this.entryPoint = entryPoint; + } + + public Role getRole() { + return Role.PROVIDER; + } + + public void activate() throws Exception { + logger = this.serviceUnit.getComponent().getLogger(); + ComponentContext ctx = this.serviceUnit.getComponent().getComponentContext(); + activated = ctx.activateEndpoint(service, endpoint); + channel = ctx.getDeliveryChannel(); + // Get the target service + ConfiguredReference referenceValue = entryPoint.getConfiguredReference(); + ConfiguredService targetServiceEndpoint = referenceValue.getTargetConfiguredServices().get(0); + // Get the business interface + Class serviceInterface = targetServiceEndpoint.getService().getServiceContract().getInterface(); + List<Class> classes = new ArrayList<Class>(); + methodMap = new HashMap<Class, Method>(); + for (Method mth : serviceInterface.getMethods()) { + Class[] params = mth.getParameterTypes(); + if (params.length != 1) { + throw new IllegalStateException("Supports only methods with one parameter"); + } + methodMap.put(params[0], mth); + classes.add(mth.getReturnType()); + classes.add(params[0]); + } + jaxbContext = JAXBContext.newInstance(classes.toArray(new Class[0])); + } + + public void deactivate() throws Exception { + ServiceEndpoint ep = activated; + activated = null; + ComponentContext ctx = this.serviceUnit.getComponent().getComponentContext(); + ctx.deactivateEndpoint(ep); + } + + public ExchangeProcessor getProcessor() { + return this; + } + + public void process(MessageExchange exchange) throws Exception { + if (exchange.getStatus() == ExchangeStatus.DONE) { + return; + } else if (exchange.getStatus() == ExchangeStatus.ERROR) { + return; + } + Object input = jaxbContext.createUnmarshaller().unmarshal(exchange.getMessage("in").getContent()); + Method method = methodMap.get(input.getClass()); + if (method == null) { + throw new IllegalStateException("Could not determine invoked web method"); + } + boolean oneWay = method.getReturnType() == null; + Object output; + try { + EntryPointContext entryPointContext = (EntryPointContext) ((ScaServiceUnit) serviceUnit) + .getTuscanyRuntime().getModuleContext().getContext(entryPoint.getName()); + InvocationHandler handler = (InvocationHandler) entryPointContext.getImplementationInstance(); + output = handler.invoke(null, method, new Object[] { input }); + } catch (UndeclaredThrowableException e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Error e) { + throw e; + } catch (Exception e) { + throw e; + } catch (Throwable e) { + throw new RuntimeException(e); + } + if (oneWay) { + exchange.setStatus(ExchangeStatus.DONE); + channel.send(exchange); + } else { + NormalizedMessage msg = exchange.createMessage(); + exchange.setMessage(msg, "out"); + StringWriter writer = new StringWriter(); + jaxbContext.createMarshaller().marshal(output, writer); + msg.setContent(new StringSource(writer.toString())); + channel.send(exchange); + } + } + + public void start() throws Exception { + } + + public void stop() throws Exception { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaLifeCycle.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaLifeCycle.java new file mode 100644 index 0000000000..499459dc71 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaLifeCycle.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca; + +import org.apache.servicemix.common.BaseComponent; +import org.apache.servicemix.common.BaseLifeCycle; + +public class ScaLifeCycle extends BaseLifeCycle { + + public ScaLifeCycle(BaseComponent component) { + super(component); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaServiceUnit.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaServiceUnit.java new file mode 100644 index 0000000000..e391edf071 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/ScaServiceUnit.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.servicemix.sca; + +import java.io.File; +import java.io.FilenameFilter; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Iterator; + +import javax.wsdl.Definition; +import javax.wsdl.factory.WSDLFactory; + +import org.apache.servicemix.common.ServiceUnit; +import org.apache.servicemix.sca.assembly.JbiBinding; +import org.apache.servicemix.sca.tuscany.CommonsLoggingMonitorFactory; +import org.apache.servicemix.sca.tuscany.TuscanyRuntime; +import org.apache.tuscany.model.assembly.Binding; +import org.apache.tuscany.model.assembly.EntryPoint; +import org.apache.tuscany.model.assembly.Module; + +public class ScaServiceUnit extends ServiceUnit { + + protected static final ThreadLocal<ScaServiceUnit> SERVICE_UNIT = new ThreadLocal<ScaServiceUnit>(); + + public static ScaServiceUnit getCurrentScaServiceUnit() { + return SERVICE_UNIT.get(); + } + + protected TuscanyRuntime tuscanyRuntime; + protected ClassLoader classLoader; + + public void init() throws Exception { + SERVICE_UNIT.set(this); + createScaRuntime(); + createEndpoints(); + SERVICE_UNIT.set(null); + } + + protected void createScaRuntime() throws Exception { + File root = new File(getRootPath()); + File[] files = root.listFiles(new JarFileFilter()); + URL[] urls = new URL[files.length + 1]; + for (int i = 0; i < files.length; i++) { + urls[i] = files[i].toURL(); + } + urls[urls.length - 1] = root.toURL(); + classLoader = new URLClassLoader(urls, getClass().getClassLoader()); + + tuscanyRuntime = new TuscanyRuntime(getName(), getRootPath(), classLoader, new CommonsLoggingMonitorFactory()); + } + + protected void createEndpoints() throws Exception { + Module module = tuscanyRuntime.getModuleComponent().getModuleImplementation(); + for (Iterator i = module.getEntryPoints().iterator(); i.hasNext();) { + EntryPoint entryPoint = (EntryPoint) i.next(); + Binding binding = (Binding) entryPoint.getBindings().get(0); + if (binding instanceof JbiBinding) { + JbiBinding jbiBinding = (JbiBinding) binding; + ScaEndpoint endpoint = new ScaEndpoint(entryPoint); + endpoint.setServiceUnit(this); + endpoint.setService(jbiBinding.getServiceName()); + endpoint.setEndpoint(jbiBinding.getEndpointName()); + endpoint.setInterfaceName(jbiBinding.getInterfaceName()); + Definition definition = jbiBinding.getDefinition(); + if (definition != null) { + endpoint.setDefinition(definition); + endpoint.setDescription(WSDLFactory.newInstance().newWSDLWriter().getDocument(definition)); + } + addEndpoint(endpoint); + } + } + } + + private static class JarFileFilter implements FilenameFilter { + public boolean accept(File dir, String name) { + return name.endsWith(".jar"); + } + } + + public TuscanyRuntime getTuscanyRuntime() { + return tuscanyRuntime; + } + + @Override + public void start() throws Exception { + tuscanyRuntime.start(); + super.start(); + } + + @Override + public void stop() throws Exception { + super.stop(); + tuscanyRuntime.stop(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/JbiAssemblyFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/JbiAssemblyFactory.java new file mode 100644 index 0000000000..ef7812f175 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/JbiAssemblyFactory.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.assembly; + +import org.apache.tuscany.model.assembly.AssemblyFactory; + +/** + * The <b>Factory</b> for the model. + */ +public interface JbiAssemblyFactory extends AssemblyFactory { + + /** + * Returns a new JbiBinding + */ + JbiBinding createJbiBinding(); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/JbiBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/JbiBinding.java new file mode 100644 index 0000000000..8bfbf80590 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/JbiBinding.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.servicemix.sca.assembly; + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.PortType; +import javax.wsdl.Service; +import javax.xml.namespace.QName; + +import org.apache.tuscany.model.assembly.Binding; + +public interface JbiBinding extends Binding { + + /** + * Returns the URI of the WSDL port for this binding. + * @return the URI of the WSDL port for this binding + */ + String getPortURI(); + + /** + * Set the URI of the WSDL port for this binding. + * @param portURI the URI of the WSDL port + */ + void setPortURI(String portURI); + + /** + * Returns the service name. + * @return the service name + */ + QName getServiceName(); + + /** + * Returns the endpoint name. + * @return the endpoint name + */ + String getEndpointName(); + + /** + * Returns the interface name. + * @returnthe interface name + */ + QName getInterfaceName(); + + /** + * Returns the WSDL definition containing the WSDL port. + * @return the WSDL definition containing the WSDL port + */ + Definition getDefinition(); + + /** + * Returns the the WSDL service. + * @return the WSDL service + */ + Service getService(); + + /** + * Returns the WSDL port defining this binding. + * @return the WSDL port defining this binding + */ + Port getPort(); + + /** + * Returns the WSDL port type. + * @return the WSDL port type + */ + PortType getPortType(); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/impl/JbiAssemblyFactoryImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/impl/JbiAssemblyFactoryImpl.java new file mode 100644 index 0000000000..4cd6a98689 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/impl/JbiAssemblyFactoryImpl.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.servicemix.sca.assembly.impl; + +import org.apache.servicemix.sca.assembly.JbiAssemblyFactory; +import org.apache.servicemix.sca.assembly.JbiBinding; +import org.apache.tuscany.model.assembly.impl.AssemblyFactoryImpl; + +/** + * An implementation of the model <b>Factory</b>. + */ +public class JbiAssemblyFactoryImpl extends AssemblyFactoryImpl implements JbiAssemblyFactory { + + /** + * Creates an instance of the factory. + */ + public JbiAssemblyFactoryImpl() { + super(); + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiAssemblyFactory#createJbiBinding() + */ + public JbiBinding createJbiBinding() { + return new JbiBindingImpl(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/impl/JbiBindingImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/impl/JbiBindingImpl.java new file mode 100644 index 0000000000..e44b9c6f45 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/assembly/impl/JbiBindingImpl.java @@ -0,0 +1,166 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.assembly.impl; + +import java.util.List; + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.PortType; +import javax.wsdl.Service; +import javax.xml.namespace.QName; + +import org.apache.servicemix.sca.assembly.JbiBinding; +import org.apache.tuscany.model.assembly.AssemblyModelContext; +import org.apache.tuscany.model.assembly.impl.BindingImpl; + +/** + * An implementation of the model object '<em><b>Web Service Binding</b></em>'. + */ +public class JbiBindingImpl extends BindingImpl implements JbiBinding { + + private String portURI; + private QName serviceName; + private String endpointName; + private QName interfaceName; + private Definition definition; + private Service service; + private PortType portType; + private Port port; + + + /** + * Constructor + */ + protected JbiBindingImpl() { + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#getPortURI() + */ + public String getPortURI() { + return portURI; + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#setPortURI(java.lang.String) + */ + public void setPortURI(String portURI) { + this.portURI = portURI; + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#getServiceName() + */ + public QName getServiceName() { + return serviceName; + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#getEndpointName() + */ + public String getEndpointName() { + return endpointName; + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#getInterfaceName() + */ + public QName getInterfaceName() { + return interfaceName; + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#getDefinition() + */ + public Definition getDefinition() { + return definition; + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#getService() + */ + public Service getService() { + return service; + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#getPort() + */ + public Port getPort() { + return port; + } + + /* (non-Javadoc) + * @see org.apache.servicemix.sca.assembly.JbiBinding#getPortType() + */ + public PortType getPortType() { + return portType; + } + + /** + * @see org.apache.tuscany.model.assembly.impl.BindingImpl#initialize(org.apache.tuscany.model.assembly.AssemblyModelContext) + */ + public void initialize(AssemblyModelContext modelContext) { + if (isInitialized()) + return; + super.initialize(modelContext); + + // Get the service name and endpoint name + String[] parts = split(portURI); + serviceName = new QName(parts[0], parts[1]); + endpointName = parts[2]; + + // Load the WSDL definitions for the given namespace + List<Definition> definitions = modelContext.getAssemblyLoader().loadDefinitions(parts[0]); + if (definitions != null) { + for (Definition definition : definitions) { + Service service = definition.getService(serviceName); + if (service != null) { + Port port = service.getPort(endpointName); + if (port != null) { + this.service = service; + this.port = port; + this.portType = port.getBinding().getPortType(); + this.interfaceName = portType.getQName(); + this.definition = definition; + return; + } + } + } + } + } + + protected String[] split(String uri) { + char sep; + uri = uri.trim(); + if (uri.indexOf('/') > 0) { + sep = '/'; + } else { + sep = ':'; + } + int idx1 = uri.lastIndexOf(sep); + int idx2 = uri.lastIndexOf(sep, idx1 - 1); + String epName = uri.substring(idx1 + 1); + String svcName = uri.substring(idx2 + 1, idx1); + String nsUri = uri.substring(0, idx2); + return new String[] { nsUri, svcName, epName }; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/ExternalJbiServiceBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/ExternalJbiServiceBuilder.java new file mode 100644 index 0000000000..e5a7b59a75 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/ExternalJbiServiceBuilder.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.builder; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Map; +import java.util.Set; + +import org.apache.servicemix.sca.assembly.JbiBinding; +import org.apache.servicemix.sca.config.ExternalJbiServiceContextFactory; +import org.apache.servicemix.sca.handler.ExternalJbiServiceClient; +import org.apache.tuscany.core.builder.BuilderException; +import org.apache.tuscany.core.builder.ContextFactoryBuilder; +import org.apache.tuscany.core.config.JavaIntrospectionHelper; +import org.apache.tuscany.core.context.QualifiedName; +import org.apache.tuscany.core.injection.SingletonObjectFactory; +import org.apache.tuscany.core.invocation.InvocationConfiguration; +import org.apache.tuscany.core.invocation.MethodHashMap; +import org.apache.tuscany.core.invocation.ProxyConfiguration; +import org.apache.tuscany.core.invocation.impl.InvokerInterceptor; +import org.apache.tuscany.core.invocation.spi.ProxyFactory; +import org.apache.tuscany.core.invocation.spi.ProxyFactoryFactory; +import org.apache.tuscany.core.message.MessageFactory; +import org.apache.tuscany.core.runtime.RuntimeContext; +import org.apache.tuscany.core.system.annotation.Autowire; +import org.apache.tuscany.model.assembly.AssemblyModelObject; +import org.apache.tuscany.model.assembly.ConfiguredService; +import org.apache.tuscany.model.assembly.ExternalService; +import org.apache.tuscany.model.assembly.Service; +import org.apache.tuscany.model.assembly.ServiceContract; +import org.apache.tuscany.model.scdl.WebServiceBinding; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +/** + * Creates a <code>RuntimeConfigurationBuilder</code> for an external service configured with the {@link WebServiceBinding} + */ +@Scope("MODULE") +public class ExternalJbiServiceBuilder implements ContextFactoryBuilder { + + private RuntimeContext runtimeContext; + + private ProxyFactoryFactory proxyFactoryFactory; + + private MessageFactory messageFactory; + + private ContextFactoryBuilder policyBuilder; + + public ExternalJbiServiceBuilder() { + } + + @Init(eager = true) + public void init() { + runtimeContext.addBuilder(this); + } + + /** + * @param runtimeContext The runtimeContext to set. + */ + @Autowire + public void setRuntimeContext(RuntimeContext runtimeContext) { + this.runtimeContext = runtimeContext; + } + + /** + * Sets the factory used to construct proxies implmementing the business interface required by a reference + */ + @Autowire + public void setProxyFactoryFactory(ProxyFactoryFactory factory) { + this.proxyFactoryFactory = factory; + } + + /** + * Sets the factory used to construct invocation messages + * + * @param msgFactory + */ + @Autowire + public void setMessageFactory(MessageFactory msgFactory) { + this.messageFactory = msgFactory; + } + + /** + * Sets a builder responsible for creating source-side and target-side invocation chains for a reference. The + * reference builder may be hierarchical, containing other child reference builders that operate on specific + * metadata used to construct and invocation chain. + * + * @see org.apache.tuscany.core.builder.impl.HierarchicalBuilder + */ + public void setPolicyBuilder(ContextFactoryBuilder builder) { + policyBuilder = builder; + } + + public void build(AssemblyModelObject object) throws BuilderException { + if (!(object instanceof ExternalService)) { + return; + } + ExternalService externalService = (ExternalService) object; + if (externalService.getBindings().size() < 1 || !(externalService.getBindings().get(0) instanceof JbiBinding)) { + return; + } + + ExternalJbiServiceClient externalJbiServiceClient = new ExternalJbiServiceClient(externalService); + ExternalJbiServiceContextFactory config = new ExternalJbiServiceContextFactory(externalService.getName(), new SingletonObjectFactory<ExternalJbiServiceClient>(externalJbiServiceClient)); + + ConfiguredService configuredService = externalService.getConfiguredService(); + Service service = configuredService.getService(); + ServiceContract serviceContract = service.getServiceContract(); + Map<Method, InvocationConfiguration> iConfigMap = new MethodHashMap(); + ProxyFactory proxyFactory = proxyFactoryFactory.createProxyFactory(); + Set<Method> javaMethods = JavaIntrospectionHelper.getAllUniqueMethods(serviceContract.getInterface()); + for (Method method : javaMethods) { + InvocationConfiguration iConfig = new InvocationConfiguration(method); + iConfigMap.put(method, iConfig); + } + QualifiedName qName = new QualifiedName(externalService.getName() + "/" + service.getName()); + ProxyConfiguration pConfiguration = new ProxyConfiguration(qName, iConfigMap, serviceContract.getInterface().getClassLoader(), messageFactory); + proxyFactory.setBusinessInterface(serviceContract.getInterface()); + proxyFactory.setProxyConfiguration(pConfiguration); + config.addTargetProxyFactory(service.getName(), proxyFactory); + configuredService.setProxyFactory(proxyFactory); + if (policyBuilder != null) { + // invoke the reference builder to handle additional policy metadata + policyBuilder.build(configuredService); + } + // add tail interceptor + for (InvocationConfiguration iConfig : (Collection<InvocationConfiguration>) iConfigMap.values()) { + iConfig.addTargetInterceptor(new InvokerInterceptor()); + } + + externalService.getConfiguredService().setContextFactory(config); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/ExternalJbiServiceWireBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/ExternalJbiServiceWireBuilder.java new file mode 100644 index 0000000000..1dc7d9f454 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/ExternalJbiServiceWireBuilder.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.servicemix.sca.builder; + +import org.apache.servicemix.sca.config.ExternalJbiServiceContextFactory; +import org.apache.servicemix.sca.handler.ExternalJbiServiceTargetInvoker; +import org.apache.tuscany.core.builder.BuilderConfigException; +import org.apache.tuscany.core.builder.WireBuilder; +import org.apache.tuscany.core.context.ScopeContext; +import org.apache.tuscany.core.invocation.InvocationConfiguration; +import org.apache.tuscany.core.invocation.spi.ProxyFactory; +import org.apache.tuscany.core.runtime.RuntimeContext; +import org.apache.tuscany.core.system.annotation.Autowire; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +@Scope("MODULE") +public class ExternalJbiServiceWireBuilder implements WireBuilder { + + private RuntimeContext runtimeContext; + + /** + * Constructs a new ExternalWebServiceWireBuilder. + */ + public ExternalJbiServiceWireBuilder() { + super(); + } + + @Autowire + public void setRuntimeContext(RuntimeContext context) { + runtimeContext = context; + } + + @Init(eager=true) + public void init() { + runtimeContext.addBuilder(this); + } + + public void connect(ProxyFactory sourceFactory, ProxyFactory targetFactory, Class targetType, boolean downScope, ScopeContext targetScopeContext) throws BuilderConfigException { + if (!(ExternalJbiServiceContextFactory.class.isAssignableFrom(targetType))) { + return; + } + for (InvocationConfiguration sourceInvocationConfig : sourceFactory.getProxyConfiguration().getInvocationConfigurations().values()) { + ExternalJbiServiceTargetInvoker invoker = new ExternalJbiServiceTargetInvoker(sourceFactory.getProxyConfiguration().getTargetName(), sourceInvocationConfig.getMethod(), targetScopeContext); + sourceInvocationConfig.setTargetInvoker(invoker); + } + } + + public void completeTargetChain(ProxyFactory targetFactory, Class targetType, ScopeContext targetScopeContext) + throws BuilderConfigException { + //TODO implement + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/JbiServiceEntryPointBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/JbiServiceEntryPointBuilder.java new file mode 100644 index 0000000000..af83c7c714 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/builder/JbiServiceEntryPointBuilder.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.builder; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.servicemix.sca.assembly.JbiBinding; +import org.apache.servicemix.sca.config.JbiServiceEntryPointContextFactory; +import org.apache.tuscany.core.builder.BuilderException; +import org.apache.tuscany.core.builder.ContextFactoryBuilder; +import org.apache.tuscany.core.builder.impl.EntryPointContextFactory; +import org.apache.tuscany.core.config.JavaIntrospectionHelper; +import org.apache.tuscany.core.context.AggregateContext; +import org.apache.tuscany.core.context.QualifiedName; +import org.apache.tuscany.core.invocation.Interceptor; +import org.apache.tuscany.core.invocation.InvocationConfiguration; +import org.apache.tuscany.core.invocation.InvocationRuntimeException; +import org.apache.tuscany.core.invocation.ProxyConfiguration; +import org.apache.tuscany.core.invocation.TargetInvoker; +import org.apache.tuscany.core.invocation.spi.ProxyFactory; +import org.apache.tuscany.core.invocation.spi.ProxyFactoryFactory; +import org.apache.tuscany.core.message.Message; +import org.apache.tuscany.core.message.MessageFactory; +import org.apache.tuscany.core.runtime.RuntimeContext; +import org.apache.tuscany.core.system.annotation.Autowire; +import org.apache.tuscany.model.assembly.AssemblyModelObject; +import org.apache.tuscany.model.assembly.ConfiguredService; +import org.apache.tuscany.model.assembly.EntryPoint; +import org.apache.tuscany.model.assembly.Service; +import org.apache.tuscany.model.assembly.ServiceContract; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +@Scope("MODULE") +public class JbiServiceEntryPointBuilder implements ContextFactoryBuilder<AggregateContext> { + + private RuntimeContext runtimeContext; + + private ProxyFactoryFactory proxyFactoryFactory; + + private MessageFactory messageFactory; + + private ContextFactoryBuilder policyBuilder; + + public JbiServiceEntryPointBuilder() { + } + + @Init(eager = true) + public void init() { + runtimeContext.addBuilder(this); + } + + /** + * @param runtimeContext The runtimeContext to set. + */ + @Autowire + public void setRuntimeContext(RuntimeContext runtimeContext) { + this.runtimeContext = runtimeContext; + } + + /** + * Sets the factory used to construct proxies implmementing the business interface required by a reference + */ + @Autowire + public void setProxyFactoryFactory(ProxyFactoryFactory factory) { + this.proxyFactoryFactory = factory; + } + + /** + * Sets the factory used to construct invocation messages + * + * @param msgFactory + */ + @Autowire + public void setMessageFactory(MessageFactory msgFactory) { + this.messageFactory = msgFactory; + } + + /** + * Sets a builder responsible for creating source-side and target-side invocation chains for a reference. The + * reference builder may be hierarchical, containing other child reference builders that operate on specific + * metadata used to construct and invocation chain. + * + * @see org.apache.tuscany.core.builder.impl.HierarchicalBuilder + */ + public void setPolicyBuilder(ContextFactoryBuilder builder) { + policyBuilder = builder; + } + + public void build(AssemblyModelObject object) throws BuilderException { + if (!(object instanceof EntryPoint)) { + return; + } + EntryPoint entryPoint = (EntryPoint) object; + if (entryPoint.getBindings().size() < 1 || !(entryPoint.getBindings().get(0) instanceof JbiBinding)) { + return; + } + + EntryPointContextFactory config = new JbiServiceEntryPointContextFactory(entryPoint.getName(), entryPoint.getConfiguredService().getService().getName(), messageFactory); + + ConfiguredService configuredService = entryPoint.getConfiguredService(); + Service service = configuredService.getService(); + ServiceContract serviceContract = service.getServiceContract(); + Map<Method, InvocationConfiguration> iConfigMap = new HashMap<Method, InvocationConfiguration>(); + ProxyFactory proxyFactory = proxyFactoryFactory.createProxyFactory(); + Set<Method> javaMethods = JavaIntrospectionHelper.getAllUniqueMethods(serviceContract.getInterface()); + for (Method method : javaMethods) { + InvocationConfiguration iConfig = new InvocationConfiguration(method); + iConfigMap.put(method, iConfig); + } + QualifiedName qName = new QualifiedName(entryPoint.getConfiguredReference().getTargetConfiguredServices().get(0).getAggregatePart().getName() + "/" + service.getName()); + ProxyConfiguration pConfiguration = new ProxyConfiguration(qName, iConfigMap, serviceContract.getInterface().getClassLoader(), messageFactory); + proxyFactory.setBusinessInterface(serviceContract.getInterface()); + proxyFactory.setProxyConfiguration(pConfiguration); + config.addSourceProxyFactory(service.getName(), proxyFactory); + configuredService.setProxyFactory(proxyFactory); + if (policyBuilder != null) { + // invoke the reference builder to handle additional policy metadata + policyBuilder.build(configuredService); + } + // add tail interceptor + for (InvocationConfiguration iConfig : (Collection<InvocationConfiguration>) iConfigMap.values()) { + iConfig.addTargetInterceptor(new EntryPointInvokerInterceptor()); + } + entryPoint.getConfiguredReference().setContextFactory(config); + } + + //FIXME same as the InvokerInterceptor except that it doesn't throw an exception in setNext + // For some reason another InvokerInterceptor is added after this one, need Jim to look into it + // and figure out why. + public class EntryPointInvokerInterceptor implements Interceptor { + + public EntryPointInvokerInterceptor() { + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + TargetInvoker invoker = msg.getTargetInvoker(); + if (invoker == null) { + throw new InvocationRuntimeException("No target invoker specified on message"); + } + return invoker.invoke(msg); + } + + public void setNext(Interceptor next) { + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/config/ExternalJbiServiceContextFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/config/ExternalJbiServiceContextFactory.java new file mode 100644 index 0000000000..93b846db8a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/config/ExternalJbiServiceContextFactory.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.config; + +import org.apache.tuscany.core.builder.ObjectFactory; +import org.apache.tuscany.core.builder.impl.BaseExternalServiceContextFactory; + +public class ExternalJbiServiceContextFactory extends BaseExternalServiceContextFactory { + + public ExternalJbiServiceContextFactory(String name, ObjectFactory objectFactory) { + super(name, objectFactory); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/config/JbiServiceEntryPointContextFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/config/JbiServiceEntryPointContextFactory.java new file mode 100644 index 0000000000..b6adb6481d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/config/JbiServiceEntryPointContextFactory.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.config; + +import org.apache.tuscany.core.builder.impl.EntryPointContextFactory; +import org.apache.tuscany.core.message.MessageFactory; + +public class JbiServiceEntryPointContextFactory extends EntryPointContextFactory { + + public JbiServiceEntryPointContextFactory(String name, String referenceName, MessageFactory msgFactory) { + super(name, referenceName, msgFactory); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/handler/ExternalJbiServiceClient.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/handler/ExternalJbiServiceClient.java new file mode 100644 index 0000000000..22b457687f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/handler/ExternalJbiServiceClient.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.handler; + +import java.io.ByteArrayOutputStream; +import java.lang.reflect.Method; + +import javax.jbi.messaging.DeliveryChannel; +import javax.jbi.messaging.ExchangeStatus; +import javax.jbi.messaging.InOut; +import javax.jbi.messaging.NormalizedMessage; +import javax.xml.bind.JAXBContext; + +import org.apache.servicemix.jbi.jaxp.StringSource; +import org.apache.servicemix.sca.ScaServiceUnit; +import org.apache.servicemix.sca.assembly.JbiBinding; +import org.apache.tuscany.model.assembly.ExternalService; + +public class ExternalJbiServiceClient { + + private ExternalService externalService; + + private JbiBinding jbiBinding; + + private ScaServiceUnit serviceUnit; + + /** + * Constructs a new ExternalWebServiceClient. + * + * @param externalService + * @param wsBinding + */ + public ExternalJbiServiceClient(ExternalService externalService) { + this.serviceUnit = ScaServiceUnit.getCurrentScaServiceUnit(); + this.externalService = externalService; + this.jbiBinding = (JbiBinding) this.externalService.getBindings().get(0); + } + + /** + * Invoke an operation on the external Web service. + * + * @param method + * @param args + * @return + */ + public Object invoke(Method method, Object[] args) { + if (args == null || args.length != 1) { + throw new IllegalStateException("args should have exactly one object"); + } + try { + Object payload = args[0]; + Class inputClass = method.getParameterTypes()[0]; + Class outputClass = method.getReturnType(); + JAXBContext context = JAXBContext.newInstance(inputClass, outputClass); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + context.createMarshaller().marshal(payload, baos); + + DeliveryChannel channel = serviceUnit.getComponent().getComponentContext().getDeliveryChannel(); + // TODO: in-only case ? + // TODO: interface based routing ? + // TODO: explicit endpoint selection ? + InOut inout = channel.createExchangeFactory().createInOutExchange(); + inout.setService(jbiBinding.getServiceName()); + NormalizedMessage in = inout.createMessage(); + inout.setInMessage(in); + in.setContent(new StringSource(baos.toString())); + boolean sent = channel.sendSync(inout); + // TODO: check for error ? + NormalizedMessage out = inout.getOutMessage(); + Object response = context.createUnmarshaller().unmarshal(out.getContent()); + inout.setStatus(ExchangeStatus.DONE); + channel.send(inout); + return response; + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/handler/ExternalJbiServiceTargetInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/handler/ExternalJbiServiceTargetInvoker.java new file mode 100644 index 0000000000..cd0560c5b5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/handler/ExternalJbiServiceTargetInvoker.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.handler; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.apache.tuscany.core.context.ExternalServiceContext; +import org.apache.tuscany.core.context.InstanceContext; +import org.apache.tuscany.core.context.QualifiedName; +import org.apache.tuscany.core.context.ScopeContext; +import org.apache.tuscany.core.context.TargetException; +import org.apache.tuscany.core.invocation.Interceptor; +import org.apache.tuscany.core.invocation.TargetInvoker; +import org.apache.tuscany.core.message.Message; + +public class ExternalJbiServiceTargetInvoker implements TargetInvoker { + + private QualifiedName serviceName; + private String esName; + private Method method; + private ScopeContext container; + + private ExternalServiceContext context; + + /** + * Constructs a new ExternalJbiServiceTargetInvoker. + * @param esName + * @param container + */ + public ExternalJbiServiceTargetInvoker(QualifiedName serviceName, Method method, ScopeContext container) { + assert (serviceName != null) : "No service name specified"; + assert (method != null) : "No method specified"; + assert (container != null) : "No scope container specified"; + this.serviceName = serviceName; + this.esName = serviceName.getPartName(); + this.method = method; + this.container = container; + } + + public Object invokeTarget(Object payload) throws InvocationTargetException { + if (context == null) { + InstanceContext iContext = container.getContext(esName); + if (!(iContext instanceof ExternalServiceContext)) { + TargetException te = new TargetException("Unexpected target context type"); + te.setIdentifier(iContext.getClass().getName()); + te.addContextName(iContext.getName()); + throw te; + } + context = (ExternalServiceContext) iContext; + } + ExternalJbiServiceClient client = (ExternalJbiServiceClient) context.getImplementationInstance(true); + if (payload != null) { + return client.invoke(method, (Object[])payload); + } else { + return client.invoke(method, null); + } + } + + public boolean isCacheable() { + return false; + } + + public Message invoke(Message msg) { + try { + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (InvocationTargetException e) { + msg.setBody(e.getCause()); + } catch (Throwable e) { + msg.setBody(e); + } + return msg; + } + + public void setNext(Interceptor next) { + throw new UnsupportedOperationException(); + } + + public Object clone() { + try { + ExternalJbiServiceTargetInvoker invoker = (ExternalJbiServiceTargetInvoker) super.clone(); + invoker.container = container; + invoker.context = this.context; + invoker.esName = this.esName; + invoker.method = this.method; + invoker.serviceName = this.serviceName; + return invoker; + } catch (CloneNotSupportedException e) { + return null; // will not happen + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/loader/JbiBindingLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/loader/JbiBindingLoader.java new file mode 100644 index 0000000000..ac67433720 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/loader/JbiBindingLoader.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.servicemix.sca.loader; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.servicemix.sca.assembly.JbiAssemblyFactory; +import org.apache.servicemix.sca.assembly.JbiBinding; +import org.apache.servicemix.sca.assembly.impl.JbiAssemblyFactoryImpl; +import org.apache.tuscany.common.resource.ResourceLoader; +import org.apache.tuscany.core.config.ConfigurationLoadException; +import org.apache.tuscany.core.loader.StAXElementLoader; +import org.apache.tuscany.core.loader.StAXLoaderRegistry; +import org.apache.tuscany.core.system.annotation.Autowire; +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +@Scope("MODULE") +public class JbiBindingLoader implements StAXElementLoader<JbiBinding>{ + + public static final QName BINDING_JBI = new QName("http://www.osoa.org/xmlns/sca/0.9", "binding.jbi"); + + private static final JbiAssemblyFactory jbiFactory = new JbiAssemblyFactoryImpl(); + + private StAXLoaderRegistry registry; + + @Autowire + public void setRegistry(StAXLoaderRegistry registry) { + this.registry = registry; + } + + @Init(eager = true) + public void start() { + registry.registerLoader(this); + } + + @Destroy + public void stop() { + registry.unregisterLoader(this); + } + + public QName getXMLType() { + return BINDING_JBI; + } + + public Class<JbiBinding> getModelType() { + return JbiBinding.class; + } + + public JbiBinding load(XMLStreamReader reader, ResourceLoader resourceLoader) throws XMLStreamException, ConfigurationLoadException { + JbiBinding binding = jbiFactory.createJbiBinding(); + binding.setURI(reader.getAttributeValue(null, "uri")); + binding.setPortURI(reader.getAttributeValue(null, "port")); + return binding; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/BootstrapHelper.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/BootstrapHelper.java new file mode 100644 index 0000000000..154afe4377 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/BootstrapHelper.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.tuscany; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.stream.XMLInputFactory; + +import org.apache.tuscany.common.resource.ResourceLoader; +import org.apache.tuscany.common.resource.impl.ResourceLoaderImpl; +import org.apache.tuscany.core.builder.ContextFactoryBuilder; +import org.apache.tuscany.core.config.ConfigurationException; +import org.apache.tuscany.core.config.ModuleComponentConfigurationLoader; +import org.apache.tuscany.core.config.impl.ModuleComponentConfigurationLoaderImpl; +import org.apache.tuscany.core.config.impl.StAXModuleComponentConfigurationLoaderImpl; +import org.apache.tuscany.core.context.AggregateContext; +import org.apache.tuscany.core.context.EventContext; +import org.apache.tuscany.core.context.SystemAggregateContext; +import org.apache.tuscany.core.loader.StAXLoaderRegistry; +import org.apache.tuscany.core.loader.StAXUtil; +import org.apache.tuscany.core.system.assembly.impl.SystemAssemblyFactoryImpl; +import org.apache.tuscany.core.system.builder.SystemContextFactoryBuilder; +import org.apache.tuscany.core.system.builder.SystemEntryPointBuilder; +import org.apache.tuscany.core.system.builder.SystemExternalServiceBuilder; +import org.apache.tuscany.core.system.loader.SystemSCDLModelLoader; +import org.apache.tuscany.model.assembly.AssemblyFactory; +import org.apache.tuscany.model.assembly.AssemblyModelContext; +import org.apache.tuscany.model.assembly.ModuleComponent; +import org.apache.tuscany.model.assembly.impl.AssemblyModelContextImpl; +import org.apache.tuscany.model.assembly.loader.AssemblyModelLoader; +import org.apache.tuscany.model.scdl.loader.SCDLModelLoader; +import org.apache.tuscany.model.scdl.loader.impl.SCDLAssemblyModelLoaderImpl; + +public class BootstrapHelper { + + /** + * Returns a default AssemblyModelContext. + * + * @param classLoader the classloader to use for application artifacts + * @return a default AssemblyModelContext + */ + public static AssemblyModelContext getModelContext(ClassLoader classLoader) { + // Create an assembly model factory + AssemblyFactory modelFactory = new SystemAssemblyFactoryImpl(); + + // Create a default assembly model loader + List<SCDLModelLoader> scdlLoaders = new ArrayList<SCDLModelLoader>(); + scdlLoaders.add(new SystemSCDLModelLoader()); + AssemblyModelLoader modelLoader = new SCDLAssemblyModelLoaderImpl(scdlLoaders); + + // Create a resource loader from the supplied classloader + ResourceLoader resourceLoader = new ResourceLoaderImpl(classLoader); + + // Create an assembly model context + return new AssemblyModelContextImpl(modelFactory, modelLoader, resourceLoader); + } + + /** + * Returns a default list of configuration builders. + * + * @return a default list of configuration builders + */ + public static List<ContextFactoryBuilder> getBuilders() { + List<ContextFactoryBuilder> configBuilders = new ArrayList<ContextFactoryBuilder>(); + configBuilders.add((new SystemContextFactoryBuilder())); + configBuilders.add(new SystemEntryPointBuilder()); + configBuilders.add(new SystemExternalServiceBuilder()); + return configBuilders; + } + + private static final boolean useStax = true; + private static final String SYSTEM_LOADER_COMPONENT = "tuscany.loader"; + + /** + * Returns the default module configuration loader. + * + * @param systemContext the runtime's system context + * @param modelContext the model context the loader will use + * @return the default module configuration loader + */ + public static ModuleComponentConfigurationLoader getConfigurationLoader(SystemAggregateContext systemContext, AssemblyModelContext modelContext) throws ConfigurationException { + if (useStax) { + // Bootstrap the StAX loader module + bootstrapStaxLoader(systemContext, modelContext); + return new StAXModuleComponentConfigurationLoaderImpl(modelContext, XMLInputFactory.newInstance(), systemContext.resolveInstance(StAXLoaderRegistry.class)); + } else { + return new ModuleComponentConfigurationLoaderImpl(modelContext); + } + } + + private static AggregateContext bootstrapStaxLoader(SystemAggregateContext systemContext, AssemblyModelContext modelContext) throws ConfigurationException { + AggregateContext loaderContext = (AggregateContext) systemContext.getContext(SYSTEM_LOADER_COMPONENT); + if (loaderContext == null) { + ModuleComponent loaderComponent = StAXUtil.bootstrapLoader(SYSTEM_LOADER_COMPONENT, modelContext); + loaderContext = registerModule(systemContext, loaderComponent); + loaderContext.fireEvent(EventContext.MODULE_START, null); + } + return loaderContext; + } + + public static AggregateContext registerModule(AggregateContext parent, ModuleComponent component) throws ConfigurationException { + // register the component + parent.registerModelObject(component); + + // Get the aggregate context representing the component + return (AggregateContext) parent.getContext(component.getName()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/CommonsLoggingMonitorFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/CommonsLoggingMonitorFactory.java new file mode 100644 index 0000000000..04bcc0bcea --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/CommonsLoggingMonitorFactory.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.servicemix.sca.tuscany; + +import java.lang.ref.WeakReference; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.tuscany.common.monitor.MonitorFactory; + +public class CommonsLoggingMonitorFactory implements MonitorFactory { + + private final Map<Class<?>, WeakReference<?>> proxies = new WeakHashMap<Class<?>, WeakReference<?>>(); + + public CommonsLoggingMonitorFactory() { + } + + public <T> T getMonitor(Class<T> monitorInterface) { + T proxy = getCachedMonitor(monitorInterface); + if (proxy == null) { + proxy = createMonitor(monitorInterface); + proxies.put(monitorInterface, new WeakReference<T>(proxy)); + } + return proxy; + } + + private <T>T getCachedMonitor(Class<T> monitorInterface) { + WeakReference<T> ref = (WeakReference<T>) proxies.get(monitorInterface); + return (ref != null) ? ref.get() : null; + } + + private <T>T createMonitor(Class<T> monitorInterface) { + String className = monitorInterface.getName(); + Log logger = LogFactory.getLog(className); + InvocationHandler handler = new LoggingHandler(logger); + return (T) Proxy.newProxyInstance(monitorInterface.getClassLoader(), new Class<?>[]{monitorInterface}, handler); + } + + private static final class LoggingHandler implements InvocationHandler { + private final Log logger; + + public LoggingHandler(Log logger) { + this.logger = logger; + } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String sourceMethod = method.getName(); + if (logger.isDebugEnabled()) { + // if the only argument is a Throwable use the special logger for it + if (args != null && args.length == 1 && args[0] instanceof Throwable) { + logger.debug(sourceMethod, (Throwable) args[0]); + } else { + StringBuilder sb = new StringBuilder(); + sb.append(sourceMethod); + sb.append("("); + for (int i = 0; i < args.length; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append(args[i]); + } + sb.append(")"); + logger.debug(sb.toString()); + } + } + return null; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/TuscanyRuntime.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/TuscanyRuntime.java new file mode 100644 index 0000000000..ee5960dfb5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/servicemix/sca/tuscany/TuscanyRuntime.java @@ -0,0 +1,174 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.tuscany; + +import java.util.List; + +import org.apache.tuscany.common.monitor.MonitorFactory; +import org.apache.tuscany.common.monitor.impl.NullMonitorFactory; +import org.apache.tuscany.core.builder.ContextFactoryBuilder; +import org.apache.tuscany.core.builder.impl.DefaultWireBuilder; +import org.apache.tuscany.core.config.ConfigurationException; +import org.apache.tuscany.core.config.ModuleComponentConfigurationLoader; +import org.apache.tuscany.core.context.AggregateContext; +import org.apache.tuscany.core.context.CoreRuntimeException; +import org.apache.tuscany.core.context.EventContext; +import org.apache.tuscany.core.context.SystemAggregateContext; +import org.apache.tuscany.core.runtime.RuntimeContext; +import org.apache.tuscany.core.runtime.RuntimeContextImpl; +import org.apache.tuscany.model.assembly.AssemblyModelContext; +import org.apache.tuscany.model.assembly.ModuleComponent; +import org.apache.tuscany.model.scdl.loader.SCDLModelLoader; +import org.osoa.sca.ModuleContext; +import org.osoa.sca.SCA; +import org.osoa.sca.ServiceRuntimeException; + +public class TuscanyRuntime extends SCA { + private final TuscanyRuntime.Monitor monitor; + private final Object sessionKey = new Object(); + + private final RuntimeContext runtime; + private final AggregateContext moduleContext; + + private final ModuleComponent moduleComponent; + + private static final String SYSTEM_MODULE_COMPONENT = "org.apache.tuscany.core.system"; + + /** + * Construct a runtime using a null MonitorFactory. + * + * @param name the name of the module component + * @param uri the URI to assign to the module component + * @throws ConfigurationException if there was a problem loading the SCA configuration + * @see TuscanyRuntime#TuscanyRuntime(String, String, org.apache.tuscany.common.monitor.MonitorFactory) + */ + public TuscanyRuntime(String name, String uri) throws ConfigurationException { + this(name, uri, + Thread.currentThread().getContextClassLoader(), + new NullMonitorFactory()); + } + + /** + * Construct a runtime containing a single module component with the + * specified name. The module definition is loaded from a "/sca.module" + * resource found on the classpath of the current Thread context classloader. + * + * @param name the name of the module component + * @param uri the URI to assign to the module component + * @param classLoader the class loader to use for the assembly + * @param monitorFactory the MonitorFactory for this runtime + * @throws ConfigurationException if there was a problem loading the SCA configuration + */ + public TuscanyRuntime(String name, String uri, ClassLoader classLoader, MonitorFactory monitorFactory) throws ConfigurationException { + this.monitor = monitorFactory.getMonitor(TuscanyRuntime.Monitor.class); + + // Create an assembly model context + AssemblyModelContext modelContext = BootstrapHelper.getModelContext(classLoader); + + // Create a runtime context and start it + List<SCDLModelLoader> loaders = modelContext.getAssemblyLoader().getLoaders(); + List<ContextFactoryBuilder> configBuilders = BootstrapHelper.getBuilders(); + runtime = new RuntimeContextImpl(monitorFactory, loaders, configBuilders, new DefaultWireBuilder()); + runtime.start(); + monitor.started(runtime); + + // Load and start the system configuration + SystemAggregateContext systemContext = runtime.getSystemContext(); + ModuleComponentConfigurationLoader loader = BootstrapHelper.getConfigurationLoader(systemContext, modelContext); + ModuleComponent systemModuleComponent = loader.loadSystemModuleComponent(SYSTEM_MODULE_COMPONENT, SYSTEM_MODULE_COMPONENT); + AggregateContext context = BootstrapHelper.registerModule(systemContext, systemModuleComponent); + context.fireEvent(EventContext.MODULE_START, null); + + // Load the SCDL configuration of the application module + AggregateContext rootContext = runtime.getRootContext(); + moduleComponent = loader.loadModuleComponent(name, uri); + moduleContext = BootstrapHelper.registerModule(rootContext, moduleComponent); + } + + public ModuleComponent getModuleComponent() { + return moduleComponent; + } + + public AggregateContext getModuleContext() { + return moduleContext; + } + + /** + * Start the runtime and associate the module context with the calling thread. + */ + @Override + public void start() { + setModuleContext((ModuleContext) moduleContext); + try { + //moduleContext.start(); + moduleContext.fireEvent(EventContext.MODULE_START, null); + moduleContext.fireEvent(EventContext.REQUEST_START, null); + moduleContext.fireEvent(EventContext.SESSION_NOTIFY, sessionKey); + monitor.started(moduleContext); + } catch (CoreRuntimeException e) { + setModuleContext(null); + monitor.startFailed(moduleContext, e); + //FIXME throw a better exception + throw new ServiceRuntimeException(e); + } + } + + /** + * Disassociate the module context from the current thread and shut down the runtime. + */ + @Override + public void stop() { + setModuleContext(null); + moduleContext.fireEvent(EventContext.REQUEST_END, null); + moduleContext.fireEvent(EventContext.SESSION_END, sessionKey); + moduleContext.fireEvent(EventContext.MODULE_STOP, null); + moduleContext.stop(); + monitor.stopped(moduleContext); + runtime.stop(); + monitor.stopped(runtime); + } + + /** + * Monitor interface for a TuscanyRuntime. + */ + public static interface Monitor { + /** + * Event emitted after the runtime has been started. + * + * @param ctx the runtime's module component context + */ + void started(AggregateContext ctx); + + /** + * Event emitted when an attempt to start the runtime failed. + * + * @param ctx the runtime's module component context + * @param e the exception that caused the failure + */ + void startFailed(AggregateContext ctx, CoreRuntimeException e); + + /** + * Event emitted after the runtime has been stopped. + * + * @param ctx the runtime's module component context + */ + void stopped(AggregateContext ctx); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/JBIBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/JBIBinding.java new file mode 100644 index 0000000000..04781d6d69 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/JBIBinding.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.servicemix; + +import org.apache.tuscany.spi.model.Binding; + +/** + * Represents a JBI binding + */ +public class JBIBinding extends Binding { + + private String uri; + + private String port; + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/JBIBindingLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/JBIBindingLoader.java new file mode 100644 index 0000000000..8b6806a731 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/JBIBindingLoader.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.servicemix; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; +import org.osoa.sca.annotations.Scope; + +/** + * Loader for handling <binding.jbi> elements. + */ +@Scope("MODULE") +public class JBIBindingLoader extends LoaderExtension<JBIBinding> { + + public static final QName BINDING_JBI = new QName("http://tuscany.apache.org/xmlns/binding/rmi/1.0-SNAPSHOT", "binding.jbi"); + + public JBIBindingLoader(@Autowire LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return BINDING_JBI; + } + + public JBIBinding load(CompositeComponent parent, XMLStreamReader reader, DeploymentContext deploymentContext) throws XMLStreamException, + LoaderException { + + String port = reader.getAttributeValue(null, "port"); + String uri = reader.getAttributeValue(null, "uri"); + LoaderUtil.skipToEndElement(reader); + + JBIBinding binding = new JBIBinding(); + binding.setPort(port); + binding.setURI(uri); + + return binding; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixBuilder.java new file mode 100644 index 0000000000..227d56d0b7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixBuilder.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 pejbissions and limitations + * under the License. + */ +package org.apache.tuscany.servicemix; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.BindingBuilderExtension; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; + +/** + * Builds a Service or Reference for a JBI binding. + */ +public class ServiceMixBuilder extends BindingBuilderExtension<JBIBinding> { + + protected Class<JBIBinding> getBindingType() { + return JBIBinding.class; + } + + @SuppressWarnings( { "unchecked" }) + public SCAObject build(CompositeComponent parent, BoundServiceDefinition<JBIBinding> boundServiceDefinition, DeploymentContext deploymentContext) { + + String name = boundServiceDefinition.getName(); + + ServiceMixService serviceMixService = new ServiceMixService(name, parent, wireService, null); + + return serviceMixService; + } + + @SuppressWarnings( { "unchecked" }) + public ServiceMixReference build(CompositeComponent parent, BoundReferenceDefinition<JBIBinding> boundReferenceDefinition, + DeploymentContext deploymentContext) { + + + ServiceMixReference serviceMixReference = new ServiceMixReference(null, parent, wireService, null, null); + + return serviceMixReference; + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixInvoker.java new file mode 100644 index 0000000000..5ad2aae7b5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixInvoker.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.servicemix; + +import java.lang.reflect.InvocationTargetException; + +import javax.jbi.messaging.DeliveryChannel; +import javax.jbi.messaging.ExchangeStatus; +import javax.jbi.messaging.InOut; +import javax.jbi.messaging.MessagingException; +import javax.jbi.messaging.NormalizedMessage; +import javax.xml.namespace.QName; + +import org.apache.servicemix.jbi.jaxp.StringSource; +import org.apache.servicemix.sca.ScaServiceUnit; +import org.apache.tuscany.spi.extension.TargetInvokerExtension; + +/** + * Invoke a JBI reference. + */ +public class ServiceMixInvoker extends TargetInvokerExtension { + + private QName serviceName; + + private ScaServiceUnit serviceUnit; + + public ServiceMixInvoker(QName serviceName) { + this.serviceName = serviceName; + this.serviceUnit = ScaServiceUnit.getCurrentScaServiceUnit(); + } + + public Object invokeTarget(Object payload) throws InvocationTargetException { + try { + DeliveryChannel channel = serviceUnit.getComponent().getComponentContext().getDeliveryChannel(); + + // TODO: in-only case ? + // TODO: interface based routing ? + // TODO: explicit endpoint selection ? + + InOut inout = channel.createExchangeFactory().createInOutExchange(); + inout.setService(serviceName); + NormalizedMessage in = inout.createMessage(); + inout.setInMessage(in); + in.setContent(new StringSource(payload.toString())); + + boolean sent = channel.sendSync(inout); + // TODO: check for error ? + + NormalizedMessage out = inout.getOutMessage(); + Object response = out.getContent(); + inout.setStatus(ExchangeStatus.DONE); + channel.send(inout); + + return response; + + } catch (MessagingException e) { + throw new InvocationTargetException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixReference.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixReference.java new file mode 100644 index 0000000000..e9898f8f15 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixReference.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.servicemix; + +import java.lang.reflect.Method; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.extension.ReferenceExtension; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; + +/** + * + */ +public class ServiceMixReference<T> extends ReferenceExtension<T> { + + private final String uri; + + public ServiceMixReference(String name, + CompositeComponent<?> parent, + WireService wireService, + String uri, + Class<T> service) + { + super(name, service, parent, wireService); + setInterface(service); + this.uri = uri; + } + + public TargetInvoker createTargetInvoker(Method arg0) { + QName serviceName = null; + ServiceMixInvoker invoker = new ServiceMixInvoker(serviceName); + return invoker; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixService.java new file mode 100644 index 0000000000..ae7e9e3f1b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/java/org/apache/tuscany/servicemix/ServiceMixService.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.servicemix; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.wire.WireService; + +/** + * + */ +public class ServiceMixService<T> extends ServiceExtension<T> { + + public ServiceMixService(String name, CompositeComponent parent, WireService wireService, Class<T> service) { + super(name, service, parent, wireService); + } + + public void start() { + super.start(); + } + + public void stop() { + super.stop(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/DISCLAIMER b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/DISCLAIMER new file mode 100644 index 0000000000..14eddf5d92 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/DISCLAIMER @@ -0,0 +1,6 @@ +Apache ServiceMix is an effort undergoing incubation at the Apache Software Foundation (ASF), sponsored by the Geronimo 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-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/LICENSE b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/LICENSE new file mode 100644 index 0000000000..6b0b1270ff --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/LICENSE @@ -0,0 +1,203 @@ + + 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-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/NOTICE b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/NOTICE new file mode 100644 index 0000000000..c035229231 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/main/jbi/META-INF/NOTICE @@ -0,0 +1,11 @@ + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Apache ServiceMix distribution. == + ========================================================================= + + This product includes software developed by + The Apache Software Foundation (http://www.apache.org/). + + Additional copyright notices and license terms applicable are + present in the licenses directory of this distribution. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/AssemblyLoaderTest.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/AssemblyLoaderTest.java new file mode 100644 index 0000000000..2edf9882ec --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/AssemblyLoaderTest.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.servicemix.sca; + +import java.io.File; +import java.net.URL; +import java.net.URLClassLoader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.servicemix.sca.assembly.JbiBinding; +import org.apache.servicemix.sca.tuscany.TuscanyRuntime; +import org.apache.tuscany.common.monitor.impl.NullMonitorFactory; +import org.apache.tuscany.model.assembly.Binding; +import org.apache.tuscany.model.assembly.Component; +import org.apache.tuscany.model.assembly.EntryPoint; +import org.apache.tuscany.model.assembly.ExternalService; +import org.apache.tuscany.model.assembly.Module; + +/** + * @author delfinoj + */ +public class AssemblyLoaderTest extends TestCase { + + protected void setUp() throws Exception { + super.setUp(); + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + } + + public void testLoader() throws Exception { + String name = "bigbank"; + String uri = getClass().getResource("bigbank/sca.module").toString(); + + URL url = getClass().getResource("bigbank/sca.module"); + URL parentUrl = new File(url.toURI()).getParentFile().toURL(); + ClassLoader cl = new URLClassLoader(new URL[] { parentUrl }, getClass().getClassLoader()); + + TuscanyRuntime rt = new TuscanyRuntime(name, uri, cl, new NullMonitorFactory()); + assertNotNull(rt); + + Module module = rt.getModuleComponent().getModuleImplementation(); + + Assert.assertTrue(module.getName().equals("org.apache.servicemix.sca.bigbank")); + + Component component = module.getComponent("AccountServiceComponent"); + Assert.assertTrue(component != null); + + EntryPoint entryPoint = module.getEntryPoint("AccountService"); + Assert.assertTrue(entryPoint != null); + + ExternalService externalService = module.getExternalService("StockQuoteService"); + Assert.assertTrue(externalService != null); + + Binding binding = externalService.getBindings().get(0); + Assert.assertTrue(binding instanceof JbiBinding); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/ScaComponentTest.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/ScaComponentTest.java new file mode 100644 index 0000000000..bd6c4b3e88 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/ScaComponentTest.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.net.URL; + +import javax.naming.InitialContext; +import javax.xml.bind.JAXBContext; +import javax.xml.namespace.QName; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; + +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.servicemix.client.DefaultServiceMixClient; +import org.apache.servicemix.client.ServiceMixClient; +import org.apache.servicemix.components.util.MockServiceComponent; +import org.apache.servicemix.jbi.container.ActivationSpec; +import org.apache.servicemix.jbi.container.JBIContainer; +import org.apache.servicemix.jbi.jaxp.SourceTransformer; +import org.apache.servicemix.jbi.jaxp.StringSource; +import org.apache.servicemix.jbi.resolver.ServiceNameEndpointResolver; +import org.apache.servicemix.sca.bigbank.stockquote.StockQuoteResponse; +import org.w3c.dom.Node; + +public class ScaComponentTest extends TestCase { + + private static Log log = LogFactory.getLog(ScaComponentTest.class); + + protected JBIContainer container; + + protected void setUp() throws Exception { + container = new JBIContainer(); + container.setUseMBeanServer(false); + container.setCreateMBeanServer(false); + container.setMonitorInstallationDirectory(false); + container.setNamingContext(new InitialContext()); + container.setEmbedded(true); + container.init(); + } + + protected void tearDown() throws Exception { + if (container != null) { + container.shutDown(); + } + } + + public void testDeploy() throws Exception { + ScaComponent component = new ScaComponent(); + container.activateComponent(component, "JSR181Component"); + + MockServiceComponent mock = new MockServiceComponent(); + mock.setService(new QName("http://www.quickstockquote.com", "StockQuoteService")); + mock.setEndpoint("StockQuoteServiceJBI"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + StockQuoteResponse r = new StockQuoteResponse(); + r.setResult(8.23f); + JAXBContext.newInstance(StockQuoteResponse.class).createMarshaller().marshal(r, baos); + mock.setResponseXml(baos.toString()); + ActivationSpec as = new ActivationSpec(); + as.setComponent(mock); + container.activateComponent(as); + + // Start container + container.start(); + + // Deploy SU + component.getServiceUnitManager().deploy("su", getServiceUnitPath("org/apache/servicemix/sca/bigbank")); + component.getServiceUnitManager().init("su", getServiceUnitPath("org/apache/servicemix/sca/bigbank")); + component.getServiceUnitManager().start("su"); + + ServiceMixClient client = new DefaultServiceMixClient(container); + Source req = new StringSource("<AccountReportRequest><CustomerID>id</CustomerID></AccountReportRequest>"); + Object rep = client.request(new ServiceNameEndpointResolver( + new QName("http://sca.servicemix.apache.org/Bigbank/Account", "AccountService")), + null, null, req); + if (rep instanceof Node) { + rep = new DOMSource((Node) rep); + } + log.info(new SourceTransformer().toString((Source) rep)); + } + + protected String getServiceUnitPath(String name) { + URL url = getClass().getClassLoader().getResource(name + "/sca.module"); + File path = new File(url.getFile()); + path = path.getParentFile(); + return path.getAbsolutePath(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountReportRequest.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountReportRequest.java new file mode 100644 index 0000000000..00c55aeffc --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountReportRequest.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.servicemix.sca.bigbank.account; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { "customerID" }) +@XmlRootElement(name = "AccountReportRequest") +public class AccountReportRequest { + + @XmlElement(name = "CustomerID") + private String customerID; + + public String getCustomerID() { + return customerID; + } + + public void setCustomerID(String customerID) { + this.customerID = customerID; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountReportResponse.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountReportResponse.java new file mode 100644 index 0000000000..f52985d2c1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountReportResponse.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.servicemix.sca.bigbank.account; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { "accountSummaries" }) +@XmlRootElement(name = "AccountReportResponse") +public class AccountReportResponse { + + @XmlElement(name = "AccountSummaries") + private List<AccountSummary> accountSummaries; + + public List<AccountSummary> getAccountSummaries() { + return accountSummaries; + } + + public void setAccountSummaries(List<AccountSummary> accountSummaries) { + this.accountSummaries = accountSummaries; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountService.java new file mode 100644 index 0000000000..5c2997f2c3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountService.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.bigbank.account; + +import org.osoa.sca.annotations.Remotable; + +@Remotable +public interface AccountService { + + public AccountReportResponse getAccountReport(AccountReportRequest request); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountServiceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountServiceImpl.java new file mode 100644 index 0000000000..f0cad13f5c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountServiceImpl.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.bigbank.account; + +import java.util.ArrayList; + +import org.apache.servicemix.sca.bigbank.accountdata.AccountDataService; +import org.apache.servicemix.sca.bigbank.accountdata.CheckingAccount; +import org.apache.servicemix.sca.bigbank.accountdata.SavingsAccount; +import org.apache.servicemix.sca.bigbank.accountdata.StockAccount; +import org.apache.servicemix.sca.bigbank.stockquote.StockQuoteRequest; +import org.apache.servicemix.sca.bigbank.stockquote.StockQuoteResponse; +import org.apache.servicemix.sca.bigbank.stockquote.StockQuoteService; +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Reference; +import org.osoa.sca.annotations.Service; + +@Service(interfaces=AccountService.class) +public class AccountServiceImpl implements AccountService { + + @Property + public String currency = "USD"; + + @Reference + public AccountDataService accountDataService; + @Reference + public StockQuoteService stockQuoteService; + + public AccountServiceImpl() { + } + + public AccountReportResponse getAccountReport(AccountReportRequest request) { + AccountReportResponse report = new AccountReportResponse(); + String customerID = request.getCustomerID(); + report.setAccountSummaries(new ArrayList<AccountSummary>()); + report.getAccountSummaries().add(getCheckAccountSummary(customerID)); + report.getAccountSummaries().add(getSavingsAccountSummary(customerID)); + report.getAccountSummaries().add(getStockAccountSummary(customerID)); + return report; + } + + private AccountSummary getCheckAccountSummary(String customerID) { + CheckingAccount checking = accountDataService.getCheckingAccount(customerID); + AccountSummary summary = new AccountSummary(); + summary.setAccountNumber(checking.getAccountNumber()); + summary.setAccountType("Checking"); + summary.setBalance(checking.getBalance()); + return summary; + } + + private AccountSummary getSavingsAccountSummary(String customerID) { + SavingsAccount savings = accountDataService.getSavingsAccount(customerID); + AccountSummary summary = new AccountSummary(); + summary.setAccountNumber(savings.getAccountNumber()); + summary.setAccountType("Savings"); + summary.setBalance(savings.getBalance()); + return summary; + } + + private AccountSummary getStockAccountSummary(String customerID) { + StockAccount stock = accountDataService.getStockAccount(customerID); + AccountSummary summary = new AccountSummary(); + summary.setAccountNumber(stock.getAccountNumber()); + summary.setAccountType("Stock"); + float quote = getQuote(stock.getSymbol()); + summary.setBalance(quote * stock.getQuantity()); + return summary; + } + + private float getQuote(String symbol) { + StockQuoteRequest req = new StockQuoteRequest(); + req.setSymbol(symbol); + StockQuoteResponse rep = stockQuoteService.getQuote(req); + return rep.getResult(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountSummary.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountSummary.java new file mode 100644 index 0000000000..f6e5a060af --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/account/AccountSummary.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.servicemix.sca.bigbank.account; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { "accountNumber", "accountType", "balance" }) +@XmlRootElement(name = "AccountSummary") +public class AccountSummary { + + @XmlElement(name = "AccountNumber") + private String accountNumber; + + @XmlElement(name = "AccountType") + private String accountType; + + @XmlElement(name = "Balance") + private float balance; + + public AccountSummary() { + } + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public String getAccountType() { + return accountType; + } + + public void setAccountType(String accountType) { + this.accountType = accountType; + } + + public float getBalance() { + return balance; + } + + public void setBalance(float balance) { + this.balance = balance; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/AccountDataService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/AccountDataService.java new file mode 100644 index 0000000000..972b9dc704 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/AccountDataService.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.servicemix.sca.bigbank.accountdata; + +public interface AccountDataService { + + CheckingAccount getCheckingAccount(String customerID); + + SavingsAccount getSavingsAccount(String customerID); + + StockAccount getStockAccount(String customerID); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/AccountDataServiceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/AccountDataServiceImpl.java new file mode 100644 index 0000000000..f9d0c08df7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/AccountDataServiceImpl.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.servicemix.sca.bigbank.accountdata; + +public class AccountDataServiceImpl implements AccountDataService { + + public CheckingAccount getCheckingAccount(String customerID) { + + CheckingAccount checkingAccount = new CheckingAccount(); + checkingAccount.setAccountNumber(customerID + "_" + "CHA12345"); + checkingAccount.setBalance(1500.0f); + + return checkingAccount; + } + + public SavingsAccount getSavingsAccount(String customerID) { + + SavingsAccount savingsAccount = new SavingsAccount(); + savingsAccount.setAccountNumber(customerID + "_" + "SAA12345"); + savingsAccount.setBalance(1500.0f); + + return savingsAccount; + } + + public StockAccount getStockAccount(String customerID) { + + StockAccount stockAccount = new StockAccount(); + stockAccount.setAccountNumber(customerID + "_" + "STA12345"); + stockAccount.setSymbol("IBM"); + stockAccount.setQuantity(100); + + return stockAccount; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/CheckingAccount.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/CheckingAccount.java new file mode 100644 index 0000000000..596dcc8d06 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/CheckingAccount.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.bigbank.accountdata; + +public class CheckingAccount { + + private String accountNumber; + private float balance; + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public float getBalance() { + return balance; + } + + public void setBalance(float balance) { + this.balance = balance; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/SavingsAccount.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/SavingsAccount.java new file mode 100644 index 0000000000..c208788ca8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/SavingsAccount.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.bigbank.accountdata; + +public class SavingsAccount { + + private String accountNumber; + private float balance; + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public float getBalance() { + return balance; + } + + public void setBalance(float balance) { + this.balance = balance; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/StockAccount.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/StockAccount.java new file mode 100644 index 0000000000..1005bceb91 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/accountdata/StockAccount.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.servicemix.sca.bigbank.accountdata; + +public class StockAccount { + + private String accountNumber; + private String symbol; + private int quantity; + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteRequest.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteRequest.java new file mode 100644 index 0000000000..4f12b18601 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteRequest.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.servicemix.sca.bigbank.stockquote; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { "symbol" }) +@XmlRootElement(name = "StockQuoteRequest") +public class StockQuoteRequest { + + @XmlElement(name = "Symbol") + private String symbol; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteResponse.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteResponse.java new file mode 100644 index 0000000000..bf2d7c7c00 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteResponse.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.servicemix.sca.bigbank.stockquote; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { "result" }) +@XmlRootElement(name = "StockQuoteResponse") +public class StockQuoteResponse { + + @XmlElement(name = "Result") + private float result; + + public float getResult() { + return result; + } + + public void setResult(float result) { + this.result = result; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteService.java new file mode 100644 index 0000000000..3fa1558907 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/java/org/apache/servicemix/sca/bigbank/stockquote/StockQuoteService.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.servicemix.sca.bigbank.stockquote; + +import org.osoa.sca.annotations.Remotable; + +@Remotable +public interface StockQuoteService { + + public StockQuoteResponse getQuote(StockQuoteRequest stockQuote); +} + + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/log4j-tests.properties b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/log4j-tests.properties new file mode 100644 index 0000000000..ec53858ed2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/log4j-tests.properties @@ -0,0 +1,38 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# The logging properties used during tests.. +# +log4j.rootLogger=DEBUG, out + +log4j.logger.org.apache.activemq=INFO +log4j.logger.org.apache.activemq.spring=WARN +log4j.logger.org.apache.activemq.store.journal=INFO +log4j.logger.org.activeio.journal=INFO + +# CONSOLE appender not used by default +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n + +# File appender +log4j.appender.out=org.apache.log4j.FileAppender +log4j.appender.out.layout=org.apache.log4j.PatternLayout +log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n +log4j.appender.out.file=target/servicemix-test.log +log4j.appender.out.append=true diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/log4j.properties b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/log4j.properties new file mode 100644 index 0000000000..992c894051 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/log4j.properties @@ -0,0 +1,39 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# +# The logging properties used during tests.. +# +log4j.rootLogger=DEBUG, stdout + +log4j.logger.org.apache.activemq=INFO +log4j.logger.org.apache.activemq.spring=WARN +log4j.logger.org.apache.activemq.store.journal=INFO +log4j.logger.org.activeio.journal=INFO + +# CONSOLE appender not used by default +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n + +# File appender +log4j.appender.out=org.apache.log4j.FileAppender +log4j.appender.out.layout=org.apache.log4j.PatternLayout +log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n +log4j.appender.out.file=target/servicemix-test.log +log4j.appender.out.append=true diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/org/apache/servicemix/sca/bigbank/account/AccountService.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/org/apache/servicemix/sca/bigbank/account/AccountService.wsdl new file mode 100644 index 0000000000..9797a5739c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/org/apache/servicemix/sca/bigbank/account/AccountService.wsdl @@ -0,0 +1,80 @@ +<?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. +--> +<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:tns="http://sca.servicemix.apache.org/Bigbank/Account" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + targetNamespace="http://sca.servicemix.apache.org/Bigbank/Account" + name="AccountService"> + + <wsdl:types> + <xsd:schema targetNamespace="http://sca.servicemix.apache.org/Bigbank/Account" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + + <xsd:element name="getAccountReportRequest" type="tns:AccountReportRequest"/> + <xsd:complexType name="AccountReportRequest"> + <xsd:sequence> + <xsd:element name="CustomerID" type="xsd:string"/> + </xsd:sequence> + </xsd:complexType> + + <xsd:element name="getAccountReportResponse" type="tns:AccountReportResponse"/> + + <xsd:complexType name="AccountReportResponse"> + <xsd:sequence> + <xsd:element name="AccountSummaries"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="AccountSummary" + type="tns:AccountSummary" maxOccurs="unbounded" minOccurs="0"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="AccountSummary"> + <xsd:sequence> + <xsd:element name="AccountNumber" type="xsd:string"/> + <xsd:element name="AccountType" type="xsd:string"/> + <xsd:element name="Balance" type="xsd:float"/> + </xsd:sequence> + </xsd:complexType> + + </xsd:schema> + </wsdl:types> + <wsdl:message name="getAccountReportRequest"> + <wsdl:part element="tns:getAccountReportRequest" name="getAccountReportRequest"/> + </wsdl:message> + <wsdl:message name="getAccountReportResponse"> + <wsdl:part element="tns:getAccountReportResponse" name="getAccountReportResponse"/> + </wsdl:message> + <wsdl:portType name="AccountService"> + <wsdl:operation name="getAccountReport"> + <wsdl:input message="tns:getAccountReportRequest"/> + <wsdl:output message="tns:getAccountReportResponse"/> + </wsdl:operation> + </wsdl:portType> + <wsdl:binding name="AccountServiceJBI" type="tns:AccountService"> + </wsdl:binding> + <wsdl:service name="AccountService"> + <wsdl:port binding="tns:AccountServiceJBI" + name="AccountServiceJBI"> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/org/apache/servicemix/sca/bigbank/sca.module b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/org/apache/servicemix/sca/bigbank/sca.module new file mode 100644 index 0000000000..ae520dd54e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/binding.servicemix/src/test/resources/org/apache/servicemix/sca/bigbank/sca.module @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="ASCII"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<module xmlns="http://www.osoa.org/xmlns/sca/0.9" xmlns:v="http://www.osoa.org/xmlns/sca/values/0.9" + + name="org.apache.servicemix.sca.bigbank"> + + <entryPoint name="AccountService"> + <interface.java interface="org.apache.servicemix.sca.bigbank.account.AccountService"/> + <interface.wsdl interface="http://sca.servicemix.apache.org/Bigbank/Account#AccountService"/> + <binding.jbi port="http://sca.servicemix.apache.org/Bigbank/Account/AccountService/AccountServiceJBI"/> + <reference>AccountServiceComponent</reference> + </entryPoint> + + <component name="AccountServiceComponent"> + <implementation.java class="org.apache.servicemix.sca.bigbank.account.AccountServiceImpl"/> + <properties> + <v:currency>EURO</v:currency> + </properties> + <references> + <v:accountDataService>AccountDataServiceComponent</v:accountDataService> + <v:stockQuoteService>StockQuoteService</v:stockQuoteService> + </references> + </component> + + <component name="AccountDataServiceComponent"> + <implementation.java class="org.apache.servicemix.sca.bigbank.accountdata.AccountDataServiceImpl"/> + </component> + + <externalService name="StockQuoteService"> + <interface.java interface="org.apache.servicemix.sca.bigbank.stockquote.StockQuoteService"/> + <binding.jbi port="http://www.quickstockquote.com/StockQuoteService/StockQuoteServiceJBI"/> + </externalService> + + <import.wsdl + location="org/apache/servicemix/sca/bigbank/account/AccountService.wsdl" + namespace="http://sca.servicemix.apache.org/Bigbank/Account" /> + +</module> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/pom.xml new file mode 100644 index 0000000000..8b255c7b2f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/pom.xml @@ -0,0 +1,63 @@ +<?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> + + <parent> + <groupId>org.apache.tuscany.sca.services</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.tuscany.sca.services.bindings</groupId> + <artifactId>parent</artifactId> + <packaging>pom</packaging> + <name>Tuscany SCA Bindings</name> + + <profiles> + <profile> + <id>full</id> + <activation> + <activeByDefault>true</activeByDefault> + </activation> + <modules> + <!-- temporary project to download and install the celtix required sun jars. The jars + are all CDDL so will be available on ibiblio when Sun releases them. This is just temporary.--> + + <module>sunjars</module> + <module>binding.celtix</module> + <module>binding.axis2</module> + <module>binding.jsonrpc</module> + <module>binding.rmi</module> + </modules> + </profile> + <profile> + <id>release</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <modules> + <module>binding.axis2</module> + <module>binding.rmi</module> + </modules> + </profile> + </profiles> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/sunjars/build.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/sunjars/build.xml new file mode 100644 index 0000000000..e6fec45356 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/sunjars/build.xml @@ -0,0 +1,56 @@ +<?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 name="CeltixSunJarsInstaller"> + <target name="checkinstalled"> + <condition property="already.installed" > + <and> + <available file="${localRepository}/javax/annotation/jsr250-api/2.0-JAXWS-2.0-EA3/jsr250-api-2.0-JAXWS-2.0-EA3.jar"/> + <available file="${localRepository}/javax/jws/jsr181-api/2.0-JAXWS-2.0-EA3/jsr181-api-2.0-JAXWS-2.0-EA3.jar"/> + <available file="${localRepository}/javax/xml/jaxws-api/2.0-JAXWS-2.0-EA3/jaxws-api-2.0-JAXWS-2.0-EA3.jar"/> + <available file="${localRepository}/com/sun/xml/saaj-impl/1.3/saaj-impl-1.3.jar"/> + <available file="${localRepository}/javax/xml/saaj-api/1.3/saaj-api-1.3.jar"/> + </and> + </condition> + <condition property="maven.suffix" value=""> + <os family="unix"/> + </condition> + <condition property="maven.suffix" value=".bat"> + <os family="windows"/> + </condition> + </target> + + <target name="installJars" depends="checkinstalled" unless="already.installed"> + <exec executable="mvn${maven.suffix}" dir="${basedir}" failonerror="false"> + <arg line="install:install-file -DgroupId=javax.annotation -DartifactId=jsr250-api -Dversion=2.0-JAXWS-2.0-EA3 -Dpackaging=jar -DgeneratePom=true -Dfile=${basedir}/target/celtix-install/celtix/lib/jsr250-api-2.0-JAXWS-2.0-EA3.jar"/> + </exec> + <exec executable="mvn${maven.suffix}" dir="${basedir}" failonerror="false"> + <arg line="install:install-file -DgroupId=javax.jws -DartifactId=jsr181-api -Dversion=2.0-JAXWS-2.0-EA3 -Dpackaging=jar -DgeneratePom=true -Dfile=${basedir}/target/celtix-install/celtix/lib/jsr181-api-2.0-JAXWS-2.0-EA3.jar"/> + </exec> + <exec executable="mvn${maven.suffix}" dir="${basedir}" failonerror="false"> + <arg line="install:install-file -DgroupId=javax.xml -DartifactId=jaxws-api -Dversion=2.0-JAXWS-2.0-EA3 -Dpackaging=jar -DgeneratePom=true -Dfile=${basedir}/target/celtix-install/celtix/lib/jaxws-api-2.0-JAXWS-2.0-EA3.jar"/> + </exec> + <exec executable="mvn${maven.suffix}" dir="${basedir}" failonerror="false"> + <arg line="install:install-file -DgroupId=javax.xml -DartifactId=saaj-api -Dversion=1.3 -Dpackaging=jar -DgeneratePom=true -Dfile=${basedir}/target/celtix-install/celtix/lib/saaj-api-1.3.jar"/> + </exec> + <exec executable="mvn${maven.suffix}" dir="${basedir}" failonerror="false"> + <arg line="install:install-file -DgroupId=com.sun.xml -DartifactId=saaj-impl -Dversion=1.3 -Dpackaging=jar -DgeneratePom=true -Dfile=${basedir}/target/celtix-install/celtix/lib/saaj-impl-1.3.jar"/> + </exec> + </target> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/sunjars/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/sunjars/pom.xml new file mode 100644 index 0000000000..d227956013 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/bindings/sunjars/pom.xml @@ -0,0 +1,102 @@ +<?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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <parent> + <groupId>org.apache.tuscany.sca.services.bindings</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>sunjars</artifactId> + <packaging>pom</packaging> + <name>Project to install the Sun jars</name> + + <properties> + <celtix.version>1.0</celtix.version> + </properties> + <repositories> + <repository> + <id>objectweb</id> + <name>ObjectWeb repo</name> + <url>http://maven.objectweb.org/maven2</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + + <build> + <plugins> + <!-- This is a "hack" to overcome the Sun jar issue. Basically, we download a + complete celtix install kit (epl version) and then extract the Sun jars that we + need and install them. We use the dependency plugin to download it from the + objectweb snapshot mirror, then use antrun to fork a build.xml that will conditionally + call mvn to install the jars if they aren't already there. --> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>dependency-maven-plugin</artifactId> + <executions> + <execution> + <id>getdeps</id> + <phase>validate</phase> + <goals> + <goal>unpack</goal> + </goals> + <configuration> + <outputDirectory>${project.build.directory}/celtix-install</outputDirectory> + <artifactItems> + <artifactItem> + <groupId>org.objectweb.celtix</groupId> + <artifactId>celtix-distribution</artifactId> + <version>${celtix.version}</version> + <classifier>bin-epl</classifier> + </artifactItem> + </artifactItems> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>install</id> + <phase>install</phase> + <goals> + <goal>run</goal> + </goals> + <configuration> + <tasks> + <ant target="installJars"> + <property name="localRepository" value="${settings.localRepository}"/> + </ant> + </tasks> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/.ruleset new file mode 100644 index 0000000000..a1547fea92 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/.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-M2/sca/services/containers/container.groovy/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/LICENSE.txt new file mode 100644 index 0000000000..0084319535 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, serviceDefinition 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-M2/sca/services/containers/container.groovy/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/pom.xml new file mode 100644 index 0000000000..30d90f503b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/pom.xml @@ -0,0 +1,77 @@ +<?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> + + <parent> + <groupId>org.apache.tuscany.sca.services.containers</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>groovy</artifactId> + <name>Apache Tuscany Groovy Container</name> + <description>Apache Tuscany Groovy Container</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>groovy</groupId> + <artifactId>groovy</artifactId> + <version>1.0-jsr-05</version> + <scope>provided</scope> + <exclusions> + <exclusion> + <groupId>cglib</groupId> + <artifactId>cglib-full</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>xpp3</groupId> + <artifactId>xpp3</artifactId> + <version>1.1.3.4-RC8</version> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>test</artifactId> + <version>${sca.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymockclassextension</artifactId> + </dependency> + </dependencies> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/AsyncGroovyInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/AsyncGroovyInvoker.java new file mode 100644 index 0000000000..f761122847 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/AsyncGroovyInvoker.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.container.groovy; + +import org.apache.tuscany.spi.component.TargetException; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; + +/** + * Responsible for performing a non-blocking dispatch on a Groovy component implementation instance + * + * @version $Rev$ $Date$ + */ +public class AsyncGroovyInvoker extends GroovyInvoker { + + private InboundWire wire; + private AsyncMonitor monitor; + private WorkContext workContext; + private Object target; + + /** + * Creates a new invoker + * + * @param operation the operation the invoker is associated with + * @param wire + * @param component the target component + * @param monitor the monitor to pass events to + * @param workContext + */ + public AsyncGroovyInvoker(String operation, + InboundWire wire, + GroovyAtomicComponent component, + AsyncMonitor monitor, + WorkContext workContext) { + super(operation, component); + this.wire = wire; + this.monitor = monitor; + this.workContext = workContext; + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + Object messageId = msg.getMessageId(); + wire.addMapping(messageId, msg.getFromAddress()); + workContext.setCurrentMessageId(null); + workContext.setCurrentCorrelationId(messageId); + invokeTarget(msg.getBody()); + // async so no return value + return null; + } catch (Throwable e) { + // FIXME need to log exceptions + monitor.executionError(e); + return null; + } + } + + public AsyncGroovyInvoker clone() throws CloneNotSupportedException { + return (AsyncGroovyInvoker) super.clone(); + } + + /** + * Resolves the target service instance or returns a cached one + */ + protected Object getInstance() throws TargetException { + if (!cacheable) { + return component.getTargetInstance(); + } else { + if (target == null) { + target = component.getTargetInstance(); + } + return target; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/AsyncMonitor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/AsyncMonitor.java new file mode 100644 index 0000000000..4da5538990 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/AsyncMonitor.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.container.groovy; + +/** + * A monitor used to log events during non-blocking invocations + * <p/> + * + * @version $$Rev$$ $$Date$$ + */ +public interface AsyncMonitor { + + /** + * Logs an exception thrown during an invocation + */ + void executionError(Throwable e); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyAtomicComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyAtomicComponent.java new file mode 100644 index 0000000000..b0ed18382f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyAtomicComponent.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.container.groovy; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.component.TargetException; +import org.apache.tuscany.spi.extension.AtomicComponentExtension; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import groovy.lang.GroovyObject; + +/** + * The Groovy atomic component implementation. Groovy implementations may be "scripts" or classes. + */ +public class GroovyAtomicComponent extends AtomicComponentExtension { + private final Class<? extends GroovyObject> groovyClass; + private final List<Class<?>> services; + //FIXME properties should move up to AtomicComponentExtension + private final Map<String, ObjectFactory> properties; + private AsyncMonitor monitor; + + public GroovyAtomicComponent(GroovyConfiguration configuration, AsyncMonitor monitor) { + super(configuration.getName(), + configuration.getParent(), + configuration.getScopeContainer(), + configuration.getWireService(), + configuration.getWorkContext(), + null, configuration.getInitLevel()); + + this.groovyClass = configuration.getGroovyClass(); + this.services = Collections.unmodifiableList(configuration.getServices()); + this.properties = new HashMap<String, ObjectFactory>(); + assert groovyClass != null; + this.monitor = monitor; + } + + public List<Class<?>> getServiceInterfaces() { + return services; + } + + public TargetInvoker createTargetInvoker(String targetName, Operation operation) { + return new GroovyInvoker(operation.getName(), this); + } + + public TargetInvoker createAsyncTargetInvoker(InboundWire wire, Operation operation) { + return new AsyncGroovyInvoker(operation.getName(), wire, this, monitor, workContext); + } + + public Object createInstance() throws ObjectCreationException { + GroovyObject instance; + try { + instance = groovyClass.newInstance(); + } catch (IllegalAccessException e) { + throw new ObjectCreationException(e); + } catch (InstantiationException e) { + throw new ObjectCreationException(e); + } + + // inject properties + for (Map.Entry<String, ObjectFactory> property : properties.entrySet()) { + instance.setProperty(property.getKey(), property.getValue().getInstance()); + } + + // inject references + for (List<OutboundWire> referenceWires : getOutboundWires().values()) { + for (OutboundWire wire : referenceWires) { + instance.setProperty(wire.getReferenceName(), wireService.createProxy(wire)); + } + } + return instance; + } + + public GroovyObject getTargetInstance() throws TargetException { + return (GroovyObject) scopeContainer.getInstance(this); + } + + public Object getServiceInstance() throws TargetException { + //TODO this should return a default service from a wire + return scopeContainer.getInstance(this); + } + + public Object getServiceInstance(String service) throws TargetException { + InboundWire wire = getInboundWire(service); + if (wire == null) { + TargetException e = new TargetException("ServiceDefinition not found"); // TODO better error message + e.setIdentifier(service); + throw e; + } + return wireService.createProxy(wire); + } + + public void addPropertyFactory(String name, ObjectFactory<?> factory) { + properties.put(name, factory); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentBuilder.java new file mode 100644 index 0000000000..4e99b888da --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentBuilder.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.groovy; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentBuilderExtension; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import groovy.lang.GroovyClassLoader; +import groovy.lang.GroovyObject; +import org.codehaus.groovy.control.CompilationFailedException; + +/** + * Extension point for creating {@link GroovyAtomicComponent}s from an assembly configuration + * + * @version $$Rev$$ $$Date$$ + */ +public class GroovyComponentBuilder extends ComponentBuilderExtension<GroovyImplementation> { + + protected Class<GroovyImplementation> getImplementationType() { + return GroovyImplementation.class; + } + + public Component build(CompositeComponent parent, + ComponentDefinition<GroovyImplementation> componentDefinition, + DeploymentContext deploymentContext) + throws BuilderConfigException { + + String name = componentDefinition.getName(); + GroovyImplementation implementation = componentDefinition.getImplementation(); + GroovyComponentType componentType = implementation.getComponentType(); + + int initLevel = componentType.getInitLevel(); + + // get list of services provided by this component + Collection<ServiceDefinition> collection = componentType.getServices().values(); + List<Class<?>> services = new ArrayList<Class<?>>(collection.size()); + for (ServiceDefinition serviceDefinition : collection) { + services.add(serviceDefinition.getServiceContract().getInterfaceClass()); + } + + // get the Groovy classloader for this deployment component + GroovyClassLoader groovyClassLoader = (GroovyClassLoader) deploymentContext.getExtension("groovy.classloader"); + if (groovyClassLoader == null) { + groovyClassLoader = new GroovyClassLoader(deploymentContext.getClassLoader()); + deploymentContext.putExtension("groovy.classloader", groovyClassLoader); + } + + // create the implementation class for the script + Class<? extends GroovyObject> groovyClass; + try { + String script = implementation.getScript(); + // REVIEW JFM can we cache the class? + groovyClass = groovyClassLoader.parseClass(script); + } catch (CompilationFailedException e) { + BuilderConfigException bce = new BuilderConfigException(e); + bce.setIdentifier(name); + throw bce; + } + // TODO deal with init and destroy + + GroovyConfiguration configuration = new GroovyConfiguration(); + configuration.setName(name); + configuration.setGroovyClass(groovyClass); + configuration.setParent(parent); + // get the scope container for this component's scope + Scope scope = componentType.getLifecycleScope(); + if (Scope.MODULE == scope) { + configuration.setScopeContainer(deploymentContext.getModuleScope()); + } else { + configuration.setScopeContainer(scopeRegistry.getScopeContainer(scope)); + } + + + configuration.setWireService(wireService); + configuration.setWorkContext(workContext); + configuration.setInitLevel(initLevel); + configuration.setServices(services); + GroovyAtomicComponent component = new GroovyAtomicComponent(configuration, null); + + // handle properties + for (Property<?> property : componentType.getProperties().values()) { + ObjectFactory<?> factory = property.getDefaultValueFactory(); + if (factory != null) { + component.addPropertyFactory(property.getName(), factory); + } + } + return component; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentType.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentType.java new file mode 100644 index 0000000000..bd54371fd7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentType.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.container.groovy; + +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceDefinition; + +/** + * Model object representing a Groovy component type + * + * @version $$Rev$$ $$Date$$ + */ +public class GroovyComponentType extends ComponentType<ServiceDefinition, ReferenceDefinition, Property<?>> { + private Scope lifecycleScope; + + public Scope getLifecycleScope() { + return lifecycleScope; + } + + public void setLifecycleScope(Scope lifecycleScope) { + this.lifecycleScope = lifecycleScope; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentTypeLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentTypeLoader.java new file mode 100644 index 0000000000..6da7840fdb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyComponentTypeLoader.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.container.groovy; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentTypeLoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.model.Scope; + +/** + * @version $Rev$ $Date$ + */ +public class GroovyComponentTypeLoader extends ComponentTypeLoaderExtension<GroovyImplementation> { + protected Class<GroovyImplementation> getImplementationClass() { + return GroovyImplementation.class; + } + + public void load(CompositeComponent parent, GroovyImplementation implementation, DeploymentContext context) + throws LoaderException { + GroovyComponentType componentType = new GroovyComponentType(); + // for now, default to module + componentType.setLifecycleScope(Scope.MODULE); + implementation.setComponentType(componentType); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyConfiguration.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyConfiguration.java new file mode 100644 index 0000000000..b9ede2d034 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyConfiguration.java @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.groovy; + +import java.lang.reflect.Member; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.wire.WireService; + +import groovy.lang.GroovyObject; + +/** + * Encapsulates confuration for a Groovy-based atomic component + * + * @version $Rev$ $Date$ + */ +public class GroovyConfiguration { + + private CompositeComponent parent; + private ScopeContainer scopeContainer; + private int initLevel; + private Map<String, Member> referenceSites = new HashMap<String, Member>(); + private Map<String, Member> propertySites = new HashMap<String, Member>(); + private Map<String, Member> callbackSites = new HashMap<String, Member>(); + private List<Class<?>> serviceInterfaces = new ArrayList<Class<?>>(); + private WireService wireService; + private WorkContext workContext; + private String name; + private Class<? extends GroovyObject> groovyClass; + private List<Class<?>> services; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Class<? extends GroovyObject> getGroovyClass() { + return groovyClass; + } + + public void setGroovyClass(Class<? extends GroovyObject> groovyClass) { + this.groovyClass = groovyClass; + } + + public CompositeComponent getParent() { + return parent; + } + + public void setParent(CompositeComponent parent) { + this.parent = parent; + } + + public ScopeContainer getScopeContainer() { + return scopeContainer; + } + + public void setScopeContainer(ScopeContainer scopeContainer) { + this.scopeContainer = scopeContainer; + } + + public List<Class<?>> getServiceInterfaces() { + return serviceInterfaces; + } + + public void addServiceInterface(Class<?> serviceInterface) { + serviceInterfaces.add(serviceInterface); + } + + public int getInitLevel() { + return initLevel; + } + + public void setInitLevel(int initLevel) { + this.initLevel = initLevel; + } + + public List<Class<?>> getServices() { + return services; + } + + public void setServices(List<Class<?>> services) { + this.services = services; + } + + public Map<String, Member> getReferenceSite() { + return referenceSites; + } + + public void addReferenceSite(String name, Member member) { + referenceSites.put(name, member); + } + + public Map<String, Member> getCallbackSite() { + return callbackSites; + } + + public void addCallbackSite(String name, Member member) { + callbackSites.put(name, member); + } + + public Map<String, Member> getPropertySites() { + return propertySites; + } + + public void addPropertySite(String name, Member member) { + propertySites.put(name, member); + } + + public WireService getWireService() { + return wireService; + } + + public void setWireService(WireService wireService) { + this.wireService = wireService; + } + + public WorkContext getWorkContext() { + return workContext; + } + + public void setWorkContext(WorkContext workContext) { + this.workContext = workContext; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyImplementation.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyImplementation.java new file mode 100644 index 0000000000..96b4a3bc2d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyImplementation.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.container.groovy; + +import org.apache.tuscany.spi.model.AtomicImplementation; + +/** + * Model object for a Groovy implementation. + */ +public class GroovyImplementation extends AtomicImplementation<GroovyComponentType> { + + //the Groovy source to be executed + private String script; + + /** + * Returns the Groovy source to be executed. + */ + public String getScript() { + return script; + } + + /** + * Sets the Groovy source to be executed. + */ + public void setScript(String script) { + this.script = script; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyInvoker.java new file mode 100644 index 0000000000..b6fdbbb0b6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/GroovyInvoker.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.container.groovy; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import groovy.lang.GroovyObject; + +/** + * Dispatches to a Groovy implementation instance + * + * @version $$Rev$$ $$Date$$ + */ +public class GroovyInvoker implements TargetInvoker, Cloneable { + + protected GroovyAtomicComponent component; + protected String operation; + protected boolean cacheable; + + public GroovyInvoker(String operation, GroovyAtomicComponent context) { + this.component = context; + this.operation = operation; + } + + public boolean isCacheable() { + return cacheable; + } + + public void setCacheable(boolean cacheable) { + this.cacheable = cacheable; + } + + public boolean isOptimizable() { + return false; + } + + /** + * Dispatches to the the target. + */ + public Object invokeTarget(final Object payload) throws InvocationTargetException { + GroovyObject target = component.getTargetInstance(); + Object[] args = (Object[]) payload; + try { + return target.invokeMethod(operation, args); + } catch (Exception ex) { + throw new InvocationTargetException(ex); + } + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (InvocationTargetException e) { + msg.setBodyWithFault(e.getCause()); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } + + public GroovyInvoker clone() throws CloneNotSupportedException { + return (GroovyInvoker) super.clone(); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/ImplementationLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/ImplementationLoader.java new file mode 100644 index 0000000000..da93abbd9d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/java/org/apache/tuscany/container/groovy/ImplementationLoader.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.groovy; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.URL; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; +import org.apache.tuscany.spi.loader.MissingResourceException; + +/** + * Loader for handling <groovy:implementation> elements. + * + * @version $Rev$ $Date$ + */ +public class ImplementationLoader extends LoaderExtension<GroovyImplementation> { + private static final QName IMPLEMENTATION_GROOVY = + new QName("http://incubator.apache.org/tuscany/xmlns/container/groovy/1.0-incubator-M2", "implementation.groovy"); + + public ImplementationLoader(@Autowire LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return IMPLEMENTATION_GROOVY; + } + + public GroovyImplementation load(CompositeComponent parent, + XMLStreamReader reader, + DeploymentContext deploymentContext) + throws XMLStreamException, LoaderException { + + String script = reader.getAttributeValue(null, "script"); + if (script == null) { + throw new MissingResourceException("No script supplied"); + } + String source = loadSource(deploymentContext.getClassLoader(), script); + + LoaderUtil.skipToEndElement(reader); + + GroovyImplementation implementation = new GroovyImplementation(); + implementation.setScript(source); + // no component type support + //registry.loadComponentType(parent, implementation, deploymentContext); + return implementation; + } + + protected String loadSource(ClassLoader cl, String resource) throws LoaderException { + URL url = cl.getResource(resource); + if (url == null) { + throw new MissingResourceException(resource); + } + InputStream is; + try { + is = url.openStream(); + } catch (IOException e) { + MissingResourceException mre = new MissingResourceException(resource, e); + mre.setIdentifier(resource); + throw mre; + } + try { + Reader reader = new InputStreamReader(is, "UTF-8"); + char[] buffer = new char[1024]; + StringBuilder source = new StringBuilder(); + int count; + while ((count = reader.read(buffer)) > 0) { + source.append(buffer, 0, count); + } + return source.toString(); + } catch (IOException e) { + LoaderException le = new LoaderException(e); + le.setIdentifier(resource); + throw le; + } finally { + try { + is.close(); + } catch (IOException e) { + // ignore + } + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/resources/META-INF/sca/groovy.system.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/resources/META-INF/sca/groovy.system.scdl new file mode 100644 index 0000000000..24fbfd5e25 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/main/resources/META-INF/sca/groovy.system.scdl @@ -0,0 +1,40 @@ +<?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. + --> +<!-- + JavaScript configuration for the launcher environment. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + + name="groovy.extension"> + + <component name="GroovyLoader"> + <system:implementation.system class="org.apache.tuscany.container.groovy.ImplementationLoader"/> + </component> + + <component name="GroovyComponentTypeLoader"> + <system:implementation.system class="org.apache.tuscany.container.groovy.GroovyComponentTypeLoader"/> + </component> + + <component name="GroovyBuilder"> + <system:implementation.system class="org.apache.tuscany.container.groovy.GroovyComponentBuilder"/> + </component> + +</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/AsyncInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/AsyncInvokerTestCase.java new file mode 100644 index 0000000000..a27bb25484 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/AsyncInvokerTestCase.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.groovy; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.services.work.WorkScheduler; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; + +import groovy.lang.GroovyObject; +import junit.framework.TestCase; +import org.apache.tuscany.container.groovy.mock.AsyncTarget; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import org.easymock.IAnswer; +import org.easymock.classextension.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class AsyncInvokerTestCase extends TestCase { + + public void testInvoke() throws Exception { + GroovyObject instance = createMock(GroovyObject.class); + expect(instance.invokeMethod("invoke", null)).andReturn(null).once(); + replay(instance); + GroovyAtomicComponent component = EasyMock.createMock(GroovyAtomicComponent.class); + expect(component.getTargetInstance()).andReturn(instance); + EasyMock.replay(component); + AsyncMonitor monitor = createMock(AsyncMonitor.class); + replay(monitor); + + WorkScheduler scheduler = createMock(WorkScheduler.class); + scheduler.scheduleWork(isA(Runnable.class)); + expectLastCall().andStubAnswer(new IAnswer() { + public Object answer() throws Throwable { + Runnable runnable = (Runnable) getCurrentArguments()[0]; + runnable.run(); + return null; + } + }); + replay(scheduler); + WorkContext context = createMock(WorkContext.class); + Method method = AsyncTarget.class.getMethod("invoke"); + method.setAccessible(true); + InboundWire wire = createMock(InboundWire.class); + AsyncGroovyInvoker invoker = new AsyncGroovyInvoker("invoke", wire, component, monitor, context); + Message msg = new MessageImpl(); + invoker.invoke(msg); + verify(instance); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/GroovyComponentTypeLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/GroovyComponentTypeLoaderTestCase.java new file mode 100644 index 0000000000..bfff4bdef7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/GroovyComponentTypeLoaderTestCase.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.container.groovy; + +import org.apache.tuscany.spi.model.Scope; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class GroovyComponentTypeLoaderTestCase extends TestCase { + + public void testLoad() throws Exception { + GroovyComponentTypeLoader loader = new GroovyComponentTypeLoader(); + GroovyImplementation impl = new GroovyImplementation(); + loader.load(null, impl, null); + GroovyComponentType type = impl.getComponentType(); + assertEquals(Scope.MODULE, type.getLifecycleScope()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/ImplementationLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/ImplementationLoaderTestCase.java new file mode 100644 index 0000000000..2af0611757 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/ImplementationLoaderTestCase.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.groovy; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.MissingResourceException; + +import junit.framework.TestCase; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.expect; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; + +/** + * @version $Rev$ $Date$ + */ +public class ImplementationLoaderTestCase extends TestCase { + private CompositeComponent parent; + private XMLStreamReader reader; + private DeploymentContext deploymentContext; + private ClassLoader classLoader; + private LoaderRegistry registry; + private ImplementationLoader loader; + + public void testNoScriptAttribute() throws LoaderException, XMLStreamException { + expect(reader.getAttributeValue(null, "script")).andReturn(null); + replay(reader); + replay(deploymentContext); + + try { + loader.load(parent, reader, deploymentContext); + fail(); + } catch (MissingResourceException e) { + // ok + } + verify(reader); + verify(deploymentContext); + } + + public void testNoScriptPresent() throws LoaderException, XMLStreamException { + expect(reader.getAttributeValue(null, "script")).andReturn("foo.groovy"); + expect(deploymentContext.getClassLoader()).andReturn(classLoader); + + replay(reader); + replay(deploymentContext); + + ImplementationLoader mockLoader = new ImplementationLoader(registry) { + protected String loadSource(ClassLoader cl, String resource) throws LoaderException { + assertSame(classLoader, cl); + assertEquals("foo.groovy", resource); + throw new MissingResourceException(resource); + } + }; + try { + mockLoader.load(parent, reader, deploymentContext); + fail(); + } catch (MissingResourceException e) { + assertEquals("foo.groovy", e.getMessage()); + } + verify(reader); + verify(deploymentContext); + } + + public void testLoadScript() throws LoaderException { + String script = loader.loadSource(getClass().getClassLoader(), + "org/apache/tuscany/container/groovy/mock/TestScript.groovy"); + assertEquals("Test Script", script); + } + + protected void setUp() throws Exception { + super.setUp(); + registry = createMock(LoaderRegistry.class); + loader = new ImplementationLoader(registry); + + parent = createMock(CompositeComponent.class); + reader = createMock(XMLStreamReader.class); + deploymentContext = createMock(DeploymentContext.class); + classLoader = createMock(ClassLoader.class); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/PropertyTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/PropertyTestCase.java new file mode 100644 index 0000000000..9b828db7eb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/PropertyTestCase.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.container.groovy; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; + +import groovy.lang.GroovyClassLoader; +import groovy.lang.GroovyObject; +import junit.framework.TestCase; +import org.apache.tuscany.container.groovy.mock.Greeting; +import static org.apache.tuscany.test.ArtifactFactory.createWireService; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import org.easymock.IAnswer; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class PropertyTestCase extends TestCase { + + private static final String SCRIPT = "import org.apache.tuscany.container.groovy.mock.Greeting;" + + "class Foo implements Greeting{" + + " String property;" + + " public String greet(String name){" + + " return property; " + + " }" + + "}"; + + private ScopeContainer scopeContainer; + private Class<? extends GroovyObject> implClass; + + /** + * Tests injecting a simple property type on a Groovy implementation instance + */ + public void testPropertyInjection() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + GroovyConfiguration configuration = new GroovyConfiguration(); + configuration.setName("source"); + configuration.setGroovyClass(implClass); + configuration.setServices(services); + configuration.setScopeContainer(scopeContainer); + configuration.setWireService(createWireService()); + GroovyAtomicComponent component = new GroovyAtomicComponent(configuration, null); + ObjectFactory<?> factory = createMock(ObjectFactory.class); + expect((String) factory.getInstance()).andReturn("bar"); + replay(factory); + component.addPropertyFactory("property", factory); + Greeting greeting = (Greeting) component.getServiceInstance(); + assertEquals("bar", greeting.greet("foo")); + } + + @SuppressWarnings("unchecked") + protected void setUp() throws Exception { + super.setUp(); + GroovyClassLoader cl = new GroovyClassLoader(getClass().getClassLoader()); + implClass = cl.parseClass(SCRIPT); + scopeContainer = createMock(ScopeContainer.class); + expect(scopeContainer.getInstance(isA(AtomicComponent.class))).andStubAnswer(new IAnswer() { + public Object answer() throws Throwable { + return ((AtomicComponent) getCurrentArguments()[0]).createInstance(); + } + }); + replay(scopeContainer); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/ScriptInvokeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/ScriptInvokeTestCase.java new file mode 100644 index 0000000000..f0ae7deb33 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/ScriptInvokeTestCase.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.container.groovy; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; + +import groovy.lang.GroovyClassLoader; +import groovy.lang.GroovyObject; +import junit.framework.TestCase; +import org.apache.tuscany.container.groovy.mock.Greeting; +import static org.apache.tuscany.test.ArtifactFactory.createWireService; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import org.easymock.IAnswer; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class ScriptInvokeTestCase extends TestCase { + + private static final String SCRIPT = "def greet(name) { return name }"; + + private Class<? extends GroovyObject> implClass; + private ScopeContainer scopeContainer; + + /** + * Tests the invocation of a Groovy "script" as opposed to a class + */ + public void testBasicScriptInvocation() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + GroovyConfiguration configuration = new GroovyConfiguration(); + configuration.setName("source"); + configuration.setGroovyClass(implClass); + configuration.setServices(services); + configuration.setScopeContainer(scopeContainer); + configuration.setWireService(createWireService()); + GroovyAtomicComponent context = new GroovyAtomicComponent(configuration, null); + GroovyObject object = (GroovyObject) context.getServiceInstance(); + assertEquals("foo", object.invokeMethod("greet", "foo")); + } + + @SuppressWarnings("unchecked") + protected void setUp() throws Exception { + super.setUp(); + GroovyClassLoader cl = new GroovyClassLoader(getClass().getClassLoader()); + implClass = cl.parseClass(SCRIPT); + scopeContainer = createMock(ScopeContainer.class); + expect(scopeContainer.getInstance(isA(AtomicComponent.class))).andStubAnswer(new IAnswer() { + public Object answer() throws Throwable { + return ((AtomicComponent) getCurrentArguments()[0]).createInstance(); + } + }); + replay(scopeContainer); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/WireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/WireTestCase.java new file mode 100644 index 0000000000..79f37f514c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/WireTestCase.java @@ -0,0 +1,189 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.groovy; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import groovy.lang.GroovyClassLoader; +import groovy.lang.GroovyObject; +import junit.framework.TestCase; +import org.apache.tuscany.container.groovy.mock.Greeting; +import static org.apache.tuscany.test.ArtifactFactory.createInboundWire; +import static org.apache.tuscany.test.ArtifactFactory.createOutboundWire; +import static org.apache.tuscany.test.ArtifactFactory.createWireService; +import static org.apache.tuscany.test.ArtifactFactory.terminateWire; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.reportMatcher; +import static org.easymock.EasyMock.verify; +import org.easymock.IAnswer; +import org.easymock.IArgumentMatcher; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class WireTestCase extends TestCase { + + private static final String SCRIPT = "import org.apache.tuscany.container.groovy.mock.Greeting;" + + "class Foo implements Greeting{" + + " Greeting wire;" + + " " + + " void setWire(Greeting ref){" + + " wire = ref;" + + " };" + + " " + + " String greet(String name){" + + " return wire.greet(name); " + + " };" + + "}"; + + private static final String SCRIPT2 = "import org.apache.tuscany.container.groovy.mock.Greeting;" + + "class Foo implements Greeting{" + + " public String greet(String name){" + + " return name; " + + " }" + + "}"; + + private Class<? extends GroovyObject> implClass1; + private Class<? extends GroovyObject> implClass2; + private ScopeContainer scopeContainer; + + /** + * Tests a basic invocation down a source wire + */ + public void testReferenceWireInvocation() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + GroovyConfiguration configuration = new GroovyConfiguration(); + configuration.setName("source"); + configuration.setGroovyClass(implClass1); + configuration.setServices(services); + configuration.setScopeContainer(scopeContainer); + configuration.setWireService(createWireService()); + GroovyAtomicComponent component = new GroovyAtomicComponent(configuration, null); + OutboundWire wire = createOutboundWire("wire", Greeting.class); + terminateWire(wire); + + TargetInvoker invoker = createMock(TargetInvoker.class); + expect(invoker.isCacheable()).andReturn(false); + Message response = new MessageImpl(); + response.setBody("foo"); + expect(invoker.invoke(eqMessage())).andReturn(response); + replay(invoker); + + for (OutboundInvocationChain chain : wire.getInvocationChains().values()) { + chain.setTargetInvoker(invoker); + } + component.addOutboundWire(wire); + Greeting greeting = (Greeting) component.getServiceInstance(); + assertEquals("foo", greeting.greet("foo")); + verify(invoker); + } + + // todo this could be generalized and moved to test module + public static Message eqMessage() { + reportMatcher(new IArgumentMatcher() { + public boolean matches(Object object) { + if (!(object instanceof Message)) { + return false; + } + final Message msg = (Message) object; + Object[] body = (Object[]) msg.getBody(); + return "foo".equals(body[0]); + } + + public void appendTo(StringBuffer stringBuffer) { + } + }); + return null; + } + + + /** + * Tests a basic invocation to a target + */ + public void testTargetInvocation() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + GroovyConfiguration configuration = new GroovyConfiguration(); + configuration.setName("source"); + configuration.setGroovyClass(implClass2); + configuration.setServices(services); + configuration.setScopeContainer(scopeContainer); + configuration.setWireService(createWireService()); + GroovyAtomicComponent component = new GroovyAtomicComponent(configuration, null); + Operation<Type> operation = new Operation<Type>("greet", null, null, null, false, null); + TargetInvoker invoker = component.createTargetInvoker(null, operation); + assertEquals("foo", invoker.invokeTarget(new String[]{"foo"})); + } + + + /** + * Tests a basic invocation down a target wire + */ + public void testTargetWireInvocation() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + GroovyConfiguration configuration = new GroovyConfiguration(); + configuration.setName("source"); + configuration.setGroovyClass(implClass2); + configuration.setServices(services); + configuration.setScopeContainer(scopeContainer); + configuration.setWireService(createWireService()); + GroovyAtomicComponent component = new GroovyAtomicComponent(configuration, null); + InboundWire wire = createInboundWire("Greeting", Greeting.class); + terminateWire(wire); + for (InboundInvocationChain chain : wire.getInvocationChains().values()) { + chain.setTargetInvoker(component.createTargetInvoker(null, chain.getOperation())); + } + component.addInboundWire(wire); + Greeting greeting = (Greeting) component.getServiceInstance("Greeting"); + assertEquals("foo", greeting.greet("foo")); + } + + protected void setUp() throws Exception { + super.setUp(); + GroovyClassLoader cl = new GroovyClassLoader(getClass().getClassLoader()); + implClass1 = cl.parseClass(SCRIPT); + implClass2 = cl.parseClass(SCRIPT2); + scopeContainer = createMock(ScopeContainer.class); + expect(scopeContainer.getInstance(isA(AtomicComponent.class))).andStubAnswer(new IAnswer() { + public Object answer() throws Throwable { + return ((AtomicComponent) getCurrentArguments()[0]).createInstance(); + } + }); + replay(scopeContainer); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/mock/AsyncTarget.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/mock/AsyncTarget.java new file mode 100644 index 0000000000..8918c3dfd5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/mock/AsyncTarget.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.groovy.mock; + +/** + * @version $Rev$ $Date$ + */ +public interface AsyncTarget { + + void invoke(); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/mock/Greeting.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/mock/Greeting.java new file mode 100644 index 0000000000..b975491f16 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/java/org/apache/tuscany/container/groovy/mock/Greeting.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.groovy.mock; + +public interface Greeting { + + String setWire(Greeting ref); + String greet(String name); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..2a04ae7a6c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/resources/META-INF/sca/default.scdl @@ -0,0 +1,28 @@ +<?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. + --> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:groovy="http://incubator.apache.org/tuscany/xmlns/container/groovy/1.0-incubator-M2" + name="groovy.test"> + + <component name="Greeting"> + <groovy:implementation.groovy script="Foo.groovy"/> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/resources/org/apache/tuscany/container/groovy/mock/TestScript.groovy b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/resources/org/apache/tuscany/container/groovy/mock/TestScript.groovy new file mode 100644 index 0000000000..f0b0a3a9d4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.groovy/src/test/resources/org/apache/tuscany/container/groovy/mock/TestScript.groovy @@ -0,0 +1 @@ +Test Script
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/pom.xml new file mode 100644 index 0000000000..f01f232c8f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/pom.xml @@ -0,0 +1,105 @@ +<?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> + + <parent> + <groupId>org.apache.tuscany.sca.services.containers</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>javascript</artifactId> + <name>Apache Tuscany JavaScript Container</name> + <description>Apache Tuscany JavaScript Container</description> + + <dependencies> + + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>core</artifactId> + <version>${sca.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>wsdl</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>rhino</groupId> + <artifactId>js</artifactId> + <version>1.6R2</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>xmlbeans</groupId> + <artifactId>xbean</artifactId> <!-- Reqd for E4X --> + <version>2.1.0</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>test</artifactId> + <version>${sca.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymockclassextension</artifactId> + </dependency> + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-api</artifactId> + </dependency> + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-impl</artifactId> + </dependency> + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <version>1.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>woodstox</groupId> + <artifactId>wstx-asl</artifactId> + </dependency> + <dependency> + <groupId>cglib</groupId> + <artifactId>cglib-nodep</artifactId> + <version>2.1_3</version> + <scope>compile</scope> + </dependency> + + </dependencies> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponent.java new file mode 100644 index 0000000000..9872788a05 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponent.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.container.javascript; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.TargetException; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.extension.AtomicComponentExtension; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; + +import org.apache.tuscany.container.javascript.rhino.RhinoScript; +import org.apache.tuscany.container.javascript.rhino.RhinoScriptInstance; + +/** + * The JavaScript component implementation. + */ +public class JavaScriptComponent extends AtomicComponentExtension { + + private final List<Class<?>> services; + + private final Map<String, Object> properties; + + private RhinoScript rhinoScript; + + public JavaScriptComponent(String name, RhinoScript rhinoScript, Map<String, Object> properties, List<Class<?>> services, + CompositeComponent parent, ScopeContainer scopeContainer, WireService wireService, + WorkContext workContext) { + super(name, parent, scopeContainer, wireService, workContext, null, 0); + + this.rhinoScript = rhinoScript; + this.services = services; + this.scope = scopeContainer.getScope(); + this.properties = properties; + } + + public Object createInstance() throws ObjectCreationException { + + Map<String, Object> context = new HashMap<String, Object>(getProperties()); + + for (List<OutboundWire> referenceWires : getOutboundWires().values()) { + for (OutboundWire wire : referenceWires) { + Object wireProxy = wireService.createProxy(wire); + //since all types that may be used in the reference interface may not be known to Rhino + //using the wireProxy as is will fail result in type conversion exceptions in cases where + //Rhino does not know enough of the tpypes used. Hence introduce a interceptor proxy, + //with weak typing (java.lang.Object) so that Rhino's call to the proxy succeeds. Then + //within this interceptor proxy perform data mediations required to correctly call the + //referenced service. + Class<?> businessInterface = wire.getServiceContract().getInterfaceClass(); + JavaScriptReferenceProxy interceptingProxy = + new JavaScriptReferenceProxy(businessInterface, + wireProxy, + rhinoScript.createInstanceScope(context)); + context.put(wire.getReferenceName(), interceptingProxy.createProxy()); + + } + } + + return rhinoScript.createRhinoScriptInstance(context); + } + + public TargetInvoker createTargetInvoker(String targetName, Operation operation) { + return new JavaScriptInvoker(operation.getName(), (Class)operation.getOutputType().getLogical(), this); + } + + // TODO: move all the following up to AtomicComponentExtension? + + public List<Class<?>> getServiceInterfaces() { + return services; + } + + public Map<String, Object> getProperties() { + return properties; + } + + public RhinoScriptInstance getTargetInstance() throws TargetException { + return (RhinoScriptInstance) scopeContainer.getInstance(this); + } + + public Object getServiceInstance() throws TargetException { + return getServiceInstance(null); + } + + public Object getServiceInstance(String service) throws TargetException { + InboundWire wire = getInboundWire(service); + if (wire == null) { + TargetException e = new TargetException("ServiceDefinition not found"); // TODO better error message + e.setIdentifier(service); + throw e; + } + return wireService.createProxy(wire); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentBuilder.java new file mode 100644 index 0000000000..1987026e59 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentBuilder.java @@ -0,0 +1,152 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.container.javascript.rhino.RhinoScript; +import org.apache.tuscany.container.javascript.utils.xmlfromxsd.XmlInstanceRegistry; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentBuilderExtension; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.PropertyValue; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceDefinition; +import org.apache.xmlbeans.XmlObject; +import org.osoa.sca.annotations.Constructor; + +/** + * Extension point for creating {@link JavaScriptComponent}s from an assembly configuration + */ +public class JavaScriptComponentBuilder extends ComponentBuilderExtension<JavaScriptImplementation> { + + private static String head = "var xmlInstanceMap = new Array();"; + + private static String part1 = "xmlInstanceMap[\""; + + private static String part2 = "\"] = "; + + private static String part3 = ";"; + + private static String getXmlObjectFunction = + "function getXmlObject(xmlElementNamespace, xmlElementName){\n" + + "return xmlInstanceMap[xmlElementNamespace + \"#\" + xmlElementName];\n}"; + + XmlInstanceRegistry xmlInstRegistry; + + @Constructor({"xmlInstRegistry"}) + public JavaScriptComponentBuilder(@Autowire XmlInstanceRegistry reg) { + this.xmlInstRegistry = reg; + } + + protected Class<JavaScriptImplementation> getImplementationType() { + return JavaScriptImplementation.class; + } + + @SuppressWarnings("unchecked") + public Component build(CompositeComponent parent, ComponentDefinition<JavaScriptImplementation> componentDefinition, + DeploymentContext deploymentContext) throws BuilderConfigException { + + String name = componentDefinition.getName(); + JavaScriptImplementation implementation = componentDefinition.getImplementation(); + JavaScriptComponentType componentType = implementation.getComponentType(); + + // get list of services provided by this component + Collection<ServiceDefinition> collection = componentType.getServices().values(); + List<Class<?>> services = new ArrayList<Class<?>>(collection.size()); + for (ServiceDefinition serviceDefinition : collection) { + services.add(serviceDefinition.getServiceContract().getInterfaceClass()); + //do this for the set of references also + enhanceRhinoScript(serviceDefinition, implementation); + } + + // get the properties for the component + Collection<PropertyValue<?>> propertyValues = componentDefinition.getPropertyValues().values(); + Map<String, Object> properties = new HashMap<String, Object>(); + for (PropertyValue propertyValue : propertyValues) { + properties.put(propertyValue.getName(), propertyValue.getValueFactory().getInstance()); + } + + RhinoScript rhinoScript = implementation.getRhinoScript(); + + // TODO: have ComponentBuilderExtension pass ScopeContainer in on build method? + ScopeContainer scopeContainer; + Scope scope = componentType.getLifecycleScope(); + if (Scope.MODULE == scope) { + scopeContainer = deploymentContext.getModuleScope(); + } else { + scopeContainer = scopeRegistry.getScopeContainer(scope); + } + + return new JavaScriptComponent(name, rhinoScript, properties, services, parent, scopeContainer, wireService, workContext); + } + + private void enhanceRhinoScript(ServiceDefinition serviceDefn, JavaScriptImplementation implementation) throws BuilderConfigException { + //if the service interface of the component is a wsdl get the wsdl interface and generate + //xml instances for the elements in it. Add these xml instances to the rhinoscript. + //TODO : when interface.wsdl and wsdl registry is integrated remove this hardcoding and + //obtain wsdl from the interface.wsdl or wsdl registry + String wsdlPath = "org/apache/tuscany/container/javascript/rhino/helloworld.wsdl"; + + //this if block is a tempfix to get other testcases working. Again when a the interface.wsdl + //extension is in place this will be deleted. Right now this is the only way we know that + //a js has to do with an interface that is wsdl. + if (!implementation.getRhinoScript().getScriptName().endsWith("e4x.js")) { + return; + } + + try { + Map<String, XmlObject> xmlInstanceMap = xmlInstRegistry.getXmlInstance(wsdlPath); + StringBuffer sb = new StringBuffer(); + + sb.append(head); + sb.append("\n"); + for (String xmlInstanceKey : xmlInstanceMap.keySet()) { + sb.append(part1); + sb.append(xmlInstanceKey); + sb.append(part2); + sb.append(xmlInstanceMap.get(xmlInstanceKey).toString()); + sb.append(part3); + sb.append("\n"); + } + // System.out.println(" **** - " + sb.toString()); + + sb.append(getXmlObjectFunction); + + RhinoScript rhinoScript = implementation.getRhinoScript(); + sb.append(rhinoScript.getScript()); + rhinoScript.setScript(sb.toString()); + rhinoScript.initScriptScope(rhinoScript.getScriptName(), sb.toString(), null, rhinoScript.getClassLoader()); + implementation.setRhinoScript(rhinoScript); + + } catch (Exception e) { + throw new BuilderConfigException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentType.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentType.java new file mode 100644 index 0000000000..31a4db14b6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentType.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.container.javascript; + +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceDefinition; + +public class JavaScriptComponentType extends ComponentType<ServiceDefinition, ReferenceDefinition, Property<?>> { + + private Scope lifecycleScope = Scope.MODULE; + + public JavaScriptComponentType() { + } + + @SuppressWarnings("unchecked") + public JavaScriptComponentType(ComponentType ct) { + // TODO: A bit hacky but this is so the non-JavaScript .componentType side file can be used for now + setInitLevel(ct.getInitLevel()); + for (Object property : ct.getProperties().values()) { + add((Property)property); + } + for (Object reference : ct.getReferences().values()) { + add((ReferenceDefinition)reference); + } + for (Object service : ct.getServices().values()) { + add((ServiceDefinition)service); + } + } + + public Scope getLifecycleScope() { + return lifecycleScope; + } + + public void setLifecycleScope(Scope lifecycleScope) { + this.lifecycleScope = lifecycleScope; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentTypeLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentTypeLoader.java new file mode 100644 index 0000000000..e28daeceb0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptComponentTypeLoader.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.container.javascript; + +import java.net.URL; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentTypeLoaderExtension; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.apache.tuscany.spi.model.ComponentType; + +import org.apache.tuscany.container.javascript.rhino.RhinoSCAConfig; +import org.apache.tuscany.container.javascript.rhino.RhinoScript; + +/** + * @version $Rev$ $Date$ + */ +public class JavaScriptComponentTypeLoader extends ComponentTypeLoaderExtension<JavaScriptImplementation> { + + private JavaInterfaceProcessorRegistry processorRegistry; + + public JavaScriptComponentTypeLoader(@Autowire JavaInterfaceProcessorRegistry processorRegistry) { + this.processorRegistry = processorRegistry; + } + + @Override + protected Class<JavaScriptImplementation> getImplementationClass() { + return JavaScriptImplementation.class; + } + + protected JavaScriptComponentType loadByIntrospection(CompositeComponent parent, + JavaScriptImplementation implementation, + DeploymentContext deploymentContext) throws + MissingResourceException, + InvalidServiceContractException { + + RhinoScript rhinoScript = implementation.getRhinoScript(); + RhinoSCAConfig scaConfig = rhinoScript.getSCAConfig(); + if (!scaConfig.hasSCAConfig()) { + throw new IllegalArgumentException( + "must use either .componentType side file or JS SCA varriable definition"); + } + + // FIXME this should be a system service, not instantiated here + JavaScriptComponentType componentType = new JavaScriptIntrospector(null, processorRegistry) + .introspectScript(scaConfig, rhinoScript.getClassLoader()); + + return componentType; + } + + protected String getResourceName(JavaScriptImplementation implementation) { + return implementation.getRhinoScript().getScriptName(); + } + + // TODO: must be possible to move all the following up in to ComponentTypeLoaderExtension + + public void load(CompositeComponent parent, JavaScriptImplementation implementation, + DeploymentContext deploymentContext) + throws LoaderException { + + URL resource = implementation.getRhinoScript().getClassLoader().getResource(getSideFileName(implementation)); + JavaScriptComponentType componentType; + if (resource == null) { + try { + componentType = loadByIntrospection(parent, implementation, deploymentContext); + } catch (InvalidServiceContractException e) { + throw new LoaderException("Invalid service contract", e); + } + } else { + componentType = loadFromSidefile(resource, deploymentContext); + } + + implementation.setComponentType(componentType); + } + + protected JavaScriptComponentType loadFromSidefile(URL url, DeploymentContext deploymentContext) + throws LoaderException { + ComponentType ct = loaderRegistry.load(null, url, ComponentType.class, deploymentContext); + JavaScriptComponentType jsct = new JavaScriptComponentType(ct); + return jsct; + } + + private String getSideFileName(JavaScriptImplementation implementation) { + String baseName = getResourceName(implementation); + int lastDot = baseName.lastIndexOf('.'); + if (lastDot != -1) { + baseName = baseName.substring(0, lastDot); + } + return baseName + ".componentType"; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptImplementation.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptImplementation.java new file mode 100644 index 0000000000..7de479f096 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptImplementation.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript; + +import org.apache.tuscany.container.javascript.rhino.RhinoScript; +import org.apache.tuscany.spi.model.AtomicImplementation; + +/** + * Model object for a JavaScript implementation. + */ +public class JavaScriptImplementation extends AtomicImplementation<JavaScriptComponentType> { + + private RhinoScript rhinoScript; + + public RhinoScript getRhinoScript() { + return rhinoScript; + } + + public void setRhinoScript(RhinoScript rhinoScript) { + this.rhinoScript = rhinoScript; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptImplementationLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptImplementationLoader.java new file mode 100644 index 0000000000..67cc35afc2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptImplementationLoader.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.URL; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.container.javascript.rhino.RhinoScript; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.osoa.sca.annotations.Constructor; + +/** + * Loader for handling JavaScript <js:implementation.js> elements. + */ +public class JavaScriptImplementationLoader extends LoaderExtension<JavaScriptImplementation> { + private static final QName IMPLEMENTATION_JAVASCRIPT = + new QName("http://incubator.apache.org/tuscany/xmlns/container/js/1.0-incubator-M2", "implementation.js"); + + @Constructor({"registry"}) + public JavaScriptImplementationLoader(@Autowire LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return IMPLEMENTATION_JAVASCRIPT; + } + + public JavaScriptImplementation load(CompositeComponent parent, XMLStreamReader reader, DeploymentContext deploymentContext) + throws XMLStreamException, LoaderException { + + String script = reader.getAttributeValue(null, "script"); + if (script == null) { + throw new MissingResourceException("No script supplied"); + } + + ClassLoader cl = deploymentContext.getClassLoader(); + String source = loadSource(cl, script); + + LoaderUtil.skipToEndElement(reader); + + JavaScriptImplementation implementation = new JavaScriptImplementation(); + RhinoScript rhinoScript = new RhinoScript(script, source, null, cl); + implementation.setRhinoScript(rhinoScript); + registry.loadComponentType(parent, implementation, deploymentContext); + return implementation; + } + + protected String loadSource(ClassLoader cl, String resource) throws LoaderException { + URL url = cl.getResource(resource); + if (url == null) { + throw new MissingResourceException(resource); + } + InputStream is; + try { + is = url.openStream(); + } catch (IOException e) { + MissingResourceException mre = new MissingResourceException(resource, e); + mre.setIdentifier(resource); + throw mre; + } + try { + Reader reader = new InputStreamReader(is, "UTF-8"); + char[] buffer = new char[1024]; + StringBuilder source = new StringBuilder(); + int count; + while ((count = reader.read(buffer)) > 0) { + source.append(buffer, 0, count); + } + return source.toString(); + } catch (IOException e) { + LoaderException le = new LoaderException(e); + le.setIdentifier(resource); + throw le; + } finally { + try { + is.close(); + } catch (IOException e) { + // ignore + } + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptIntrospector.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptIntrospector.java new file mode 100644 index 0000000000..542504b62e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptIntrospector.java @@ -0,0 +1,173 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript; + +import java.util.Iterator; +import java.util.Map; +import javax.wsdl.Definition; +import javax.wsdl.PortType; +import javax.wsdl.WSDLException; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import org.apache.tuscany.container.javascript.rhino.RhinoSCAConfig; +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistry; +import org.apache.tuscany.idl.wsdl.WSDLServiceContract; + +/** + * Introspects JavaScript files for SCA configuration + */ +public class JavaScriptIntrospector { + + private WSDLDefinitionRegistry wsdlRegistry; + private JavaInterfaceProcessorRegistry processorRegistry; + + public JavaScriptIntrospector(@Autowire WSDLDefinitionRegistry wsdlRegistry, + @Autowire JavaInterfaceProcessorRegistry processorRegistry) { + this.wsdlRegistry = wsdlRegistry; + this.processorRegistry = processorRegistry; + } + + public JavaScriptComponentType introspectScript(RhinoSCAConfig scaConfig, ClassLoader cl) + throws MissingResourceException, InvalidServiceContractException { + JavaScriptComponentType componentType = new JavaScriptComponentType(); + introspectJavaInterface(componentType, cl, scaConfig.getJavaInterface()); + introspectWSDLInterface(componentType, cl, scaConfig.getWSDLNamespace(), scaConfig.getWSDLPortType(), + scaConfig.getWSDLLocation()); + introspectReferences(componentType, cl, scaConfig.getReferences()); + introspectProperties(componentType, cl, scaConfig.getProperties()); + introspectScope(componentType, scaConfig.getScope()); + return componentType; + } + + private void introspectScope(JavaScriptComponentType componentType, Scope scope) { + if (scope != null) { + componentType.setLifecycleScope(scope); + } + } + + @SuppressWarnings("unchecked") + private void introspectJavaInterface(ComponentType componentType, ClassLoader cl, String serviceClass) + throws MissingResourceException, InvalidServiceContractException { + if (serviceClass != null) { + ServiceDefinition service = new ServiceDefinition(); + try { + ServiceContract<?> sc = processorRegistry.introspect(Class.forName(serviceClass)); + service.setServiceContract(sc); + componentType.add(service); + } catch (ClassNotFoundException e) { + throw new MissingResourceException("Interface not found", e); + } + } + } + + @SuppressWarnings("unchecked") + private void introspectWSDLInterface(ComponentType componentType, ClassLoader cl, String wsdlNamespace, + String wsdlPortType, String wsdlLocation) { + if (wsdlNamespace == null && wsdlPortType == null && wsdlLocation == null) { + return; + } + + PortType portType = null; + if (wsdlLocation != null) { + portType = readWSDLPortType(wsdlNamespace, wsdlPortType, wsdlLocation, portType); + } else { + portType = getPortType(wsdlNamespace, wsdlPortType); + } + + ServiceDefinition service = new ServiceDefinition(); + WSDLServiceContract wsdlSC = new WSDLServiceContract(); + wsdlSC.setPortType(portType); + service.setServiceContract(wsdlSC); + componentType.add(service); + } + + private PortType readWSDLPortType(String wsdlNamespace, String wsdlPortType, String wsdlLocation, + PortType portType) { + Definition wsdlDefinition; + try { + WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + wsdlDefinition = reader.readWSDL(wsdlLocation.toString()); + } catch (WSDLException e) { + throw new RuntimeException(e); + + } + Map portTypes = wsdlDefinition.getPortTypes(); + for (Iterator i = portTypes.keySet().iterator(); i.hasNext();) { + QName portTypeQN = (QName) i.next(); + if (wsdlNamespace != null) { + if (!portTypeQN.getNamespaceURI().equals(wsdlNamespace)) { + continue; + } + } + if (wsdlPortType != null) { + if (!portTypeQN.getLocalPart().equals(wsdlPortType)) { + continue; + } + } + if (portType != null) { + throw new RuntimeException("multiple matching portTypes in wsdl: " + wsdlLocation); + } + portType = (PortType) portTypes.get(portTypeQN); + } + if (portType == null) { + throw new RuntimeException("portType not found in wsdl: " + wsdlLocation); + } + return portType; + } + + private PortType getPortType(String wsdlNamespace, String wsdlPortType) { + if (wsdlPortType == null) { + throw new IllegalArgumentException("must specify the wsdlPortType in script SCA config"); + } + PortType portType = null; + if (wsdlNamespace != null) { + QName portTypeQN = new QName(wsdlNamespace.toString(), wsdlPortType.toString()); + portType = wsdlRegistry.getPortType(portTypeQN); + if (portType == null) { + throw new IllegalArgumentException("no WSDL registered for portType: " + portTypeQN); + } + } else { + // wsdlRegistry.getPortType(wsdlPortType.toString()); + if (portType == null) { + throw new IllegalArgumentException("no WSDL registered for portType:" + wsdlPortType); + } + } + return portType; + } + + + private void introspectProperties(ComponentType componentType, ClassLoader cl, Map properties) { + } + + private void introspectReferences(ComponentType componentType, ClassLoader cl, Map references) { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptInvoker.java new file mode 100644 index 0000000000..281b417d64 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptInvoker.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.container.javascript; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.tuscany.container.javascript.rhino.RhinoScriptInstance; +import org.apache.tuscany.spi.extension.TargetInvokerExtension; + +/** + * Dispatches to a JavaScript implementation instance + * + * @version $$Rev$$ $$Date$$ + */ +public class JavaScriptInvoker extends TargetInvokerExtension { + + private JavaScriptComponent context; + + private String functionName; + + private Class responseClass; + + public JavaScriptInvoker(String functionName, Class respClass, JavaScriptComponent context) { + this.functionName = functionName; + this.context = context; + this.responseClass = respClass; + } + + /** + * Invokes a function on a script instance + */ + public Object invokeTarget(final Object payload) throws InvocationTargetException { + RhinoScriptInstance target = context.getTargetInstance(); + return target.invokeFunction(functionName, (Object[]) payload, responseClass); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptRefInvocInterceptor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptRefInvocInterceptor.java new file mode 100644 index 0000000000..f8c978f833 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptRefInvocInterceptor.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript; + +import java.io.ByteArrayInputStream; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axiom.om.util.StAXUtils; +import org.apache.xmlbeans.XmlObject; +import org.mozilla.javascript.Context; +import org.mozilla.javascript.Scriptable; +import org.mozilla.javascript.ScriptableObject; +import org.mozilla.javascript.Wrapper; +import org.mozilla.javascript.xml.XMLObject; + +/** + * This Interceptor encasulates the data mediation required by the JavaScriptReferenceProxy. The + * invocation handler of this class traps the javascript reference calls, performs data mediation + * and calls then calls the actual referred service. This classes implementation is subject to + * review and change when the DataMediation infrastructure of Tuscany is ready. + * + */ +public class JavaScriptRefInvocInterceptor implements InvocationHandler { + private Object actualProxy; + + private Class wireInterface; + + private Scriptable instanceScope; + + JavaScriptRefInvocInterceptor(Object wireProxy, Class wireIfc, Scriptable instScope) { + this.actualProxy = wireProxy; + this.wireInterface = wireIfc; + this.instanceScope = instScope; + } + + public Object invoke(Object arg0, Method method, Object[] args) throws Throwable { + // TODO Auto-generated method stub + Context cx = Context.enter(); + try { + Method invokedMethod = getInvokedMethod(method.getName()); + Object[] tranformedArgs = new Object[args.length]; + for (int count = 0; count < args.length; ++count) { + tranformedArgs[count] = fromJavaScript(invokedMethod.getParameterTypes()[count], args[count]); + } + + Object response = invokedMethod.invoke(actualProxy, tranformedArgs); + response = toJavaScript(response, instanceScope, cx); + return response; + } finally { + Context.exit(); + } + } + + private Method getInvokedMethod(String methodName) { + Method[] methods = wireInterface.getMethods(); + + for (int count = 0; count < methods.length; ++count) { + if (methods[count].getName().equals(methodName)) { + return methods[count]; + } + } + throw new RuntimeException("Unable to find invocation method"); + } + + protected Object fromJavaScript(Class reqArgType, Object jsArg) throws Exception { + Object javaArg; + if (Context.getUndefinedValue().equals(jsArg)) { + javaArg = null; + } else if (jsArg instanceof XMLObject) { + // TODO: E4X Bug? Shouldn't need this copy, but without it the outer element gets lost??? + Scriptable jsXML = (Scriptable) ScriptableObject.callMethod((Scriptable) jsArg, "copy", new Object[0]); + Wrapper wrapper = (Wrapper) ScriptableObject.callMethod(jsXML, "getXmlObject", new Object[0]); + javaArg = wrapper.unwrap(); + + XMLStreamReader xmlReader = StAXUtils.createXMLStreamReader(new ByteArrayInputStream(javaArg.toString().getBytes())); + StAXOMBuilder staxOMBuilder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(), xmlReader); + javaArg = staxOMBuilder.getDocumentElement(); + } else if (jsArg instanceof Wrapper) { + javaArg = ((Wrapper) jsArg).unwrap(); + } else { + if (reqArgType != null) { + javaArg = Context.jsToJava(jsArg, reqArgType); + } else { + javaArg = Context.jsToJava(jsArg, String.class); + } + } + + return javaArg; + } + + protected Object toJavaScript(Object retVal, Scriptable scope, Context cx) throws RuntimeException { + Object jsRetVal; + if (retVal instanceof OMElement) { + try { + XmlObject xmlObject = XmlObject.Factory.parse(retVal.toString()); + Object jsXML = cx.getWrapFactory().wrap(cx, scope, xmlObject, XmlObject.class); + jsRetVal = cx.newObject(scope, "XML", new Object[] { jsXML }); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else if (retVal instanceof XmlObject) { + Object jsXML = cx.getWrapFactory().wrap(cx, scope, (XmlObject) retVal, XmlObject.class); + jsRetVal = cx.newObject(scope, "XML", new Object[] { jsXML }); + } else { + jsRetVal = Context.toObject(retVal, scope); + } + + return jsRetVal; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptReferenceProxy.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptReferenceProxy.java new file mode 100644 index 0000000000..8b432872b8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/JavaScriptReferenceProxy.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import net.sf.cglib.asm.ClassWriter; +import net.sf.cglib.asm.CodeVisitor; +import net.sf.cglib.asm.Constants; +import net.sf.cglib.asm.Type; + +import org.apache.tuscany.spi.wire.WireInvocationHandler; +import org.mozilla.javascript.Context; +import org.mozilla.javascript.Scriptable; +import org.mozilla.javascript.ScriptableObject; +import org.mozilla.javascript.Wrapper; +import org.mozilla.javascript.xml.XMLObject; + +/** + * This is a proxy that will mediate reference calls from the JavaScript. The mediation code here will be reviewed when the DataMediation + * infrastructure is ready. This proxy assmes that there is no verloading of service methods on the reference interface i.e. there are no two service + * methods that have the same method name or operation name. + */ +public class JavaScriptReferenceProxy { + + private Class interfaze; + + private Object wireProxy; + + private Scriptable instanceScope; + + public JavaScriptReferenceProxy(Class interfaze, Object wireProxy, Scriptable instScope) { + this.interfaze = interfaze; + this.wireProxy = wireProxy; + this.instanceScope = instScope; + } + + public Object createProxy() { + try { + GenericProxyClassLoader classloader = new GenericProxyClassLoader(); + final byte[] byteCode = generateGenericInterface(interfaze); + + Class genericInterface = classloader.defineClass(byteCode); + InvocationHandler proxyHandler = new JavaScriptRefInvocInterceptor(wireProxy, + interfaze, instanceScope); + // return genericInterface.cast(Proxy.newProxyInstance(classloader, new Class[]{genericInterface}, proxyHandler)); + return Proxy.newProxyInstance(classloader, + new Class[]{genericInterface}, + proxyHandler); + } catch (Exception e) { + return null; + } + } + + private static byte[] generateGenericInterface(Class serviceInterface) { + String interfazeName = serviceInterface.getCanonicalName(); + ClassWriter cw = new ClassWriter(false); + + cw.visit(Constants.V1_5, + Constants.ACC_PUBLIC + Constants.ACC_ABSTRACT + Constants.ACC_INTERFACE, + interfazeName.replace('.', + '/'), + "java/lang/Object", + null, + serviceInterface.getSimpleName() + ".java"); + + StringBuffer argsAndReturn = new StringBuffer("("); + Method[] methods = serviceInterface.getMethods(); + for (int count = 0; count < methods.length; ++count) { + argsAndReturn = new StringBuffer("("); + Class[] paramTypes = methods[count].getParameterTypes(); + Class returnType = methods[count].getReturnType(); + + for (int paramCount = 0; paramCount < paramTypes.length; ++paramCount) { + argsAndReturn.append(Type.getType(Object.class)); + } + argsAndReturn.append(")"); + argsAndReturn.append(Type.getType(Object.class)); + + Class[] exceptionTypes = methods[count].getExceptionTypes(); + String[] exceptions = new String[exceptionTypes.length]; + for (int excCount = 0; excCount < exceptionTypes.length; ++excCount) { + exceptions[excCount] = exceptionTypes[excCount].getName(); + exceptions[excCount] = exceptions[excCount].replace('.', + '/'); + } + + CodeVisitor cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_ABSTRACT, + methods[count].getName(), + argsAndReturn.toString(), + exceptions, + null); + cw.visitEnd(); + } + + cw.visitEnd(); + + return cw.toByteArray(); + } + + private class GenericProxyClassLoader extends ClassLoader { + public Class defineClass(byte[] byteArray) { + try { + return defineClass(null, + byteArray, + 0, + byteArray.length); + } catch (Throwable e) { + return null; + } + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoFunctionInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoFunctionInvoker.java new file mode 100644 index 0000000000..b2064f9110 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoFunctionInvoker.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript.rhino; + +import java.io.ByteArrayInputStream; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axiom.om.util.StAXUtils; +import org.apache.xmlbeans.XmlObject; +import org.mozilla.javascript.Context; +import org.mozilla.javascript.Function; +import org.mozilla.javascript.Scriptable; +import org.mozilla.javascript.ScriptableObject; +import org.mozilla.javascript.Wrapper; +import org.mozilla.javascript.xml.XMLObject; + +/** + * An invoker for a specific function in a JavaScript script + */ +public class RhinoFunctionInvoker { + + private Scriptable instanceScope; + + private Function function; + + private Class responseClass; + + public RhinoFunctionInvoker(Scriptable instanceScope, Function function, Class responseClass) { + this.instanceScope = instanceScope; + this.function = function; + this.responseClass = responseClass; + } + + public Object invoke(Object[] args) { + Context cx = Context.enter(); + try { + + Object[] jsArgs = toJavaScript(args, instanceScope, cx); + Object jsResponse = function.call(cx, instanceScope, instanceScope, jsArgs); + Object response = fromJavaScript(jsResponse); + return response; + + } catch ( Exception e ) { + throw new RuntimeException(e); + } + finally { + Context.exit(); + } + } + + protected Object[] toJavaScript(Object[] arg, Scriptable scope, Context cx) throws RuntimeException { + Object[] jsArgs; + if (arg == null) { + jsArgs = new Object[0]; + } else if (arg.length == 1 && arg[0] instanceof OMElement) { + try { + XmlObject xmlObject = XmlObject.Factory.parse(arg[0].toString()); + Object jsXML = cx.getWrapFactory().wrap(cx, scope, xmlObject, XmlObject.class); + jsArgs = new Object[] { cx.newObject(scope, "XML", new Object[] { jsXML }) }; + } catch ( Exception e ) { + throw new RuntimeException(e); + } + } else if (arg.length == 1 && arg[0] instanceof XmlObject) { + Object jsXML = cx.getWrapFactory().wrap(cx, scope, (XmlObject)arg[0], XmlObject.class); + jsArgs = new Object[] { cx.newObject(scope, "XML", new Object[] { jsXML }) }; + } else { + jsArgs = new Object[arg.length]; + for (int i = 0; i < jsArgs.length; i++) { + jsArgs[i] = Context.toObject(arg[i], scope); + } + } + + return jsArgs; + } + + protected Object fromJavaScript(Object o) throws Exception { + Object response; + if (Context.getUndefinedValue().equals(o)) { + response = null; + } else if (o instanceof XMLObject) { + // TODO: E4X Bug? Shouldn't need this copy, but without it the outer element gets lost??? + Scriptable jsXML = (Scriptable) ScriptableObject.callMethod((Scriptable) o, "copy", new Object[0]); + Wrapper wrapper = (Wrapper) ScriptableObject.callMethod(jsXML, "getXmlObject", new Object[0]); + response = wrapper.unwrap(); + + XMLStreamReader xmlReader = + StAXUtils.createXMLStreamReader(new ByteArrayInputStream(response.toString().getBytes())); + StAXOMBuilder staxOMBuilder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(), xmlReader); + response = staxOMBuilder.getDocumentElement(); + + } else if (o instanceof Wrapper) { + response = ((Wrapper) o).unwrap(); + } else { + if (responseClass != null) { + response = Context.jsToJava(o, responseClass); + } else { + response = Context.jsToJava(o, String.class); + } + } + return response; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoSCAConfig.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoSCAConfig.java new file mode 100644 index 0000000000..af27403c03 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoSCAConfig.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript.rhino; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.model.Scope; +import org.mozilla.javascript.Scriptable; +import org.mozilla.javascript.UniqueTag; + +/** + * Represents the variable defining the SCA aspects of the script + * <code> + * SCA = { + * javaInterface : "my.pkg.ClassName", + * wsdlPortType : "wsdlPortTypeName", + * wsdlNameSpace : "http://my.namespace.com", + * wsdlLocation : "\wsdl\mywsdl.txt", + * properties : { "foo" : ["java.lang.String", "defaultValue"],}, + * references : {}, + * scope : 'stateless'|'request'|'conversational'|'composite', + * } + * </code> + * The config must define the service with either javaInterface or wsdl. When + * using wsdl the three parameters are optional. If wsdlLocation is used that is the + * WSDL document used, and the namespace and portType parameters are only required if + * the WSDL definition defines multiple portTypes. + */ +public class RhinoSCAConfig { + + private boolean hasSCAConfig; + + private String javaInterface; + + private String wsdlLocation; + + private String wsdlNamespace; + + private String wsdlPortType; + + private Map properties; + + private Map references; + + private Scope scope; + + public RhinoSCAConfig(Scriptable scriptScope) { + Object o = scriptScope.get("SCA", scriptScope); + if (o != null && UniqueTag.NOT_FOUND != o) { + hasSCAConfig = true; + Scriptable scaVar = (Scriptable) o; + o = scaVar.get("javaInterface", scriptScope); + if (o != null && UniqueTag.NOT_FOUND != o) { + this.javaInterface = o.toString(); + } + o = scaVar.get("wsdlLocation", scriptScope); + if (o != null && UniqueTag.NOT_FOUND != o) { + this.wsdlLocation = o.toString(); + } + o = scaVar.get("wsdlPortType", scriptScope); + if (o != null && UniqueTag.NOT_FOUND != o) { + this.wsdlPortType = o.toString(); + } + o = scaVar.get("wsdlNamespace", scriptScope); + if (o != null && UniqueTag.NOT_FOUND != o) { + this.wsdlNamespace = o.toString(); + } + if (javaInterface != null) { + if (wsdlLocation != null || wsdlPortType != null || wsdlNamespace != null) { + throw new IllegalArgumentException("script SCA config defines both Java and WSDL service interface"); + } + } else { + if (wsdlLocation == null && wsdlPortType == null && wsdlNamespace == null) { + throw new IllegalArgumentException("script SCA config must define either Java or WSDL service interface"); + } + } + + this.properties = new HashMap(); + o = scaVar.get("properties", scriptScope); + if (o != null && UniqueTag.NOT_FOUND != o) { + // TODO parse properties + } + + this.references = new HashMap(); + o = scaVar.get("references", scriptScope); + if (o != null && UniqueTag.NOT_FOUND != o) { + // TODO parse references + } + + o = scaVar.get("scope", scriptScope); + if (o != null && UniqueTag.NOT_FOUND != o) { + if ("stateless".equalsIgnoreCase(String.valueOf(o))) { + this.scope = Scope.STATELESS; + } else if ("request".equalsIgnoreCase(String.valueOf(o))) { + this.scope = Scope.REQUEST; + } else if ("conversational".equalsIgnoreCase(String.valueOf(o))) { + this.scope = Scope.SESSION; // TODO: where's CONVERSATIONAL? + } else if ("composite".equalsIgnoreCase(String.valueOf(o))) { + this.scope = Scope.MODULE; // TODO: composite = MODULE for now? + } else { + throw new IllegalArgumentException("invalid scope value: " + o); + } + } + + } + } + + public boolean hasSCAConfig() { + return hasSCAConfig; + } + + public String getJavaInterface() { + return javaInterface; + } + + public Map getProperties() { + return properties; + } + + public Map getReferences() { + return references; + } + + public String getWSDLLocation() { + return wsdlLocation; + } + + public String getWSDLNamespace() { + return wsdlNamespace; + } + + public String getWSDLPortType() { + return wsdlPortType; + } + + public Scope getScope() { + return scope; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoScript.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoScript.java new file mode 100644 index 0000000000..3552372223 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoScript.java @@ -0,0 +1,210 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript.rhino; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.mozilla.javascript.Context; +import org.mozilla.javascript.ContextFactory; +import org.mozilla.javascript.ImporterTopLevel; +import org.mozilla.javascript.Script; +import org.mozilla.javascript.Scriptable; + +/** + * A RhinoScript represents a compiled JavaScript script + */ +public class RhinoScript { + + protected String scriptName; + + protected String script; + + protected Scriptable scriptScope; + + protected Map<String, Class> responseClasses; + + protected ClassLoader classLoader; + + /* + * Enable dynamic scopes so a script can be used concurrently with a global shared scope and individual execution scopes. See + * http://www.mozilla.org/rhino/scopes.html + */ + private static class MyFactory extends ContextFactory { + protected boolean hasFeature(Context cx, int featureIndex) { + if (featureIndex == Context.FEATURE_DYNAMIC_SCOPE) { + return true; + } + return super.hasFeature(cx, featureIndex); + } + } + + static { + ContextFactory.initGlobal(new MyFactory()); + } + + /** + * Create a new RhinoScript. + * + * @param scriptName + * the name of the script. Can be anything, only used in messages to identify the script + * @param script + * the complete script + */ + public RhinoScript(String scriptName, String script) { + this(scriptName, script, (Map) null, null); + } + + /** + * Create a new RhinoInvoker. + * + * @param scriptName + * the name of the script. Can be anything, only used in messages to identify the script + * @param script + * the complete script + * @param context + * name-value pairs that are added in to the scope where the script is compiled. May be null. The value objects are made available to + * the script by using a variable with the name. + * @param classLoader + * the ClassLoader Rhino should use to locate any user Java classes used in the script + */ + public RhinoScript(String scriptName, String script, Map context, ClassLoader classLoader) { + this.scriptName = scriptName; + this.script = script; + this.responseClasses = new HashMap<String, Class>(); + this.classLoader = classLoader; + initScriptScope(scriptName, script, context, classLoader); + } + + /** + * Create a new invokeable instance of the script + * + * @return a RhinoScriptInstance + */ + public RhinoScriptInstance createRhinoScriptInstance() { + return createRhinoScriptInstance(null); + } + + /** + * Create a new invokeable instance of the script + * + * @param context + * objects to add to scope of the script instance + * @return a RhinoScriptInstance + */ + public RhinoScriptInstance createRhinoScriptInstance(Map<String, Object> context) { + Scriptable instanceScope = createInstanceScope(context); + RhinoScriptInstance rsi = new RhinoScriptInstance(scriptScope, instanceScope, context, responseClasses); + return rsi; + } + + /** + * Initialize the Rhino Scope for this script instance + */ + public Scriptable createInstanceScope(Map<String, Object> context) { + Context cx = Context.enter(); + try { + + Scriptable instanceScope = cx.newObject(scriptScope); + instanceScope.setPrototype(scriptScope); + instanceScope.setParentScope(null); + + addContexts(instanceScope, context); + + return instanceScope; + + } finally { + Context.exit(); + } + } + + /** + * Create a Rhino scope and compile the script into it + */ + public void initScriptScope(String fileName, String scriptCode, Map context, ClassLoader cl) { + Context cx = Context.enter(); + try { + if (cl != null) { + // TODO: broken with the way the tuscany launcher now uses class loaders + // cx.setApplicationClassLoader(cl); + } + this.scriptScope = new ImporterTopLevel(cx, true); + Script compiledScript = cx.compileString(scriptCode, fileName, 1, null); + compiledScript.exec(cx, scriptScope); + addContexts(scriptScope, context); + + } finally { + Context.exit(); + } + } + + /** + * Add the context to the scope. This will make the objects available to a script by using the name it was added with. + */ + protected void addContexts(Scriptable scope, Map contexts) { + if (contexts != null) { + for (Iterator i = contexts.keySet().iterator(); i.hasNext();) { + String name = (String) i.next(); + Object value = contexts.get(name); + if (value != null) { + scope.put(name, scope, Context.toObject(value, scope)); + } + } + } + } + + public String getScript() { + return script; + } + + public String getScriptName() { + return scriptName; + } + + public Scriptable getScriptScope() { + return scriptScope; + } + + public Map<String, Class> getResponseClasses() { + return responseClasses; + } + + public ClassLoader getClassLoader() { + return classLoader; + } + + /** + * Set the Java type of a response value. JavaScript is dynamically typed so Rhino cannot always work out what the intended Java type of a + * response should be, for example should the statement "return 42" be a Java int, or Integer or Double etc. When Rhino can't determine the type + * it will default to returning a String, using this method enables overriding the Rhino default to use a specific Java type. + */ + public void setResponseClass(String functionName, Class responseClasses) { + this.responseClasses.put(functionName, responseClasses); + } + + public RhinoSCAConfig getSCAConfig() { + return new RhinoSCAConfig(getScriptScope()); + } + + public void setScript(String script) { + this.script = script; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptInstance.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptInstance.java new file mode 100644 index 0000000000..508bc2a90a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptInstance.java @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript.rhino; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.mozilla.javascript.Context; +import org.mozilla.javascript.Function; +import org.mozilla.javascript.Scriptable; +import org.mozilla.javascript.UniqueTag; + +/** + * An invokeable instance of a JavaScript script. + */ +public class RhinoScriptInstance { + + private Scriptable scriptScope; + + private Scriptable instanceScope; + + private Map<String, Class> responseClasses; + + public RhinoScriptInstance(Scriptable scriptScope, Scriptable instanceScope, Map<String, Object> context, Map<String, Class> responseClasses) { + this.scriptScope = scriptScope; + this.instanceScope = instanceScope; + this.responseClasses = responseClasses; + if (this.responseClasses == null) { + this.responseClasses = new HashMap<String, Class>(); + } + addContexts(instanceScope, context); + } + + public Object invokeFunction(String functionName, Object[] args) { + return invokeFunction(functionName, args, null); + } + + public Object invokeFunction(String functionName, Object[] args, Class respClass) { + RhinoFunctionInvoker invoker = createRhinoFunctionInvoker(functionName, respClass); + return invoker.invoke(args); + } + + public RhinoFunctionInvoker createRhinoFunctionInvoker(String functionName) { + return createRhinoFunctionInvoker(functionName, null); + } + + + public RhinoFunctionInvoker createRhinoFunctionInvoker(String functionName, Class responseClass) { + Function function = getFunction(functionName); + //Class responseClass = responseClasses.get(functionName); + RhinoFunctionInvoker invoker = new RhinoFunctionInvoker(instanceScope, function, responseClass); + return invoker; + } + + /** + * Add the context to the scope. This will make the objects available to a script by using the name it was added with. + */ + protected void addContexts(Scriptable scope, Map contexts) { + if (contexts != null) { + Context.enter(); + try { + for (Iterator i = contexts.keySet().iterator(); i.hasNext();) { + String name = (String) i.next(); + Object value = contexts.get(name); + if (value != null) { + scope.put(name, scope, Context.toObject(value, scope)); + } + } + } finally { + Context.exit(); + } + } + } + + /** + * Get the Rhino Function object for the named script function + */ + protected Function getFunction(String functionName) { + + Object handleObj = scriptScope.get(functionName, instanceScope); + if (UniqueTag.NOT_FOUND.equals(handleObj)) { + // Bit of a hack so E4X scripts don't need to define a function for every operation + handleObj = scriptScope.get("process", instanceScope); + } + if (!(handleObj instanceof Function)) { + throw new RuntimeException("script function '" + functionName + "' is undefined or not a function"); + } + + return (Function) handleObj; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/CmdLineArgsHandler.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/CmdLineArgsHandler.java new file mode 100644 index 0000000000..b724b33ac3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/CmdLineArgsHandler.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.container.javascript.utils.xmlfromxsd; + +/** + * This interface is to be implemented by classes that wish to + * handle commandline arguments. + * + */ +public interface CmdLineArgsHandler { + public void handleArgument(String optionFlag, String argValue) throws IllegalArgumentException; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/CmdLineArgsProcessor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/CmdLineArgsProcessor.java new file mode 100644 index 0000000000..914f1d03f2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/CmdLineArgsProcessor.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.container.javascript.utils.xmlfromxsd; + +/** + * This class provides a generic command line arguments processing utility. The processArgs + * method of this class processes the command line arguments that could contain option flags, + * options and values and calls a ArgumentHanlder instance for handling the agruments. + * + */ +public class CmdLineArgsProcessor { + private String printUsageMessage = "No hints available on Usage!"; + + private CmdLineArgsHandler argsHandler = null; + + public static final String HYPEN = "-"; + + public void processArgs(String[] args) { + try { + if (args.length == 0) { + printUsage(); + } else { + parseAndHandleArgs(args); + } + } catch (Exception e) { + System.out.println("Exception in processing argument - " + e); + printUsage(); + } + + } + + public void parseAndHandleArgs(String[] args) throws Exception { + int index = 0; + while (index < args.length - 1) { + if (args[index].startsWith(HYPEN) && !args[index + 1].startsWith(HYPEN)) { + argsHandler.handleArgument(args[index].substring(1), args[index + 1]); + index = index + 2; + } else { + throw new IllegalArgumentException("Wrong Usage of options!"); + } + } + } + + protected void printUsage() { + + } + + public CmdLineArgsHandler getArgsHandler() { + return argsHandler; + } + + public void setArgsHandler(CmdLineArgsHandler argsHandler) { + this.argsHandler = argsHandler; + } + + public String getPrintUsageMessage() { + return printUsageMessage; + } + + public void setPrintUsageMessage(String printUsageMessage) { + this.printUsageMessage = printUsageMessage; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/TuscanySampleXmlUtil.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/TuscanySampleXmlUtil.java new file mode 100644 index 0000000000..a0155c76e6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/TuscanySampleXmlUtil.java @@ -0,0 +1,1097 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript.utils.xmlfromxsd; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.SchemaParticle; +import org.apache.xmlbeans.SchemaLocalElement; +import org.apache.xmlbeans.SchemaProperty; +import org.apache.xmlbeans.GDuration; +import org.apache.xmlbeans.GDurationBuilder; +import org.apache.xmlbeans.GDate; +import org.apache.xmlbeans.GDateBuilder; +import org.apache.xmlbeans.XmlAnySimpleType; +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlInteger; +import org.apache.xmlbeans.XmlDate; +import org.apache.xmlbeans.XmlDateTime; +import org.apache.xmlbeans.XmlTime; +import org.apache.xmlbeans.XmlGYear; +import org.apache.xmlbeans.XmlGYearMonth; +import org.apache.xmlbeans.XmlGMonth; +import org.apache.xmlbeans.XmlGMonthDay; +import org.apache.xmlbeans.XmlGDay; +import org.apache.xmlbeans.XmlDecimal; +import org.apache.xmlbeans.XmlDuration; +import org.apache.xmlbeans.soap.SchemaWSDLArrayType; +import org.apache.xmlbeans.soap.SOAPArrayType; +import org.apache.xmlbeans.impl.util.Base64; +import org.apache.xmlbeans.impl.util.HexBin; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.Random; +import java.util.Set; +import java.util.HashSet; +import java.util.Arrays; + +import javax.xml.namespace.QName; + +/** + * This class is a replication of the XMLBeans SampleXMLutil class. This replication + * is required to overide the XMLBeans behaviour of this class in certain places. Since + * most methods of the XMLBeans implementation of this class is private, no overiding + * has been possible using inheritance. Hence this replication. + * + */ +public class TuscanySampleXmlUtil { + private static final String BLANK_STRING = " "; + + private boolean generate_sample_data = false; + + private boolean _soapEnc; + + private static final int MAX_ELEMENTS = 1000; + + private int _nElements; + + boolean flag = true; + + private TuscanySampleXmlUtil(boolean soapEnc) { + _soapEnc = soapEnc; + } + + public TuscanySampleXmlUtil() { + this(false); + } + + public String createSampleForType(SchemaType sType) { + XmlObject object = XmlObject.Factory.newInstance(); + XmlCursor cursor = object.newCursor(); + // Skip the document node + cursor.toNextToken(); + // Using the type and the cursor, call the utility method to get a + // sample XML payload for that Schema element + createSampleForType(sType, cursor); + // Cursor now contains the sample payload + // Pretty print the result. Note that the cursor is positioned at the + // end of the doc so we use the original xml object that the cursor was + // created upon to do the xmlText() against. + XmlOptions options = new XmlOptions(); + options.put(XmlOptions.SAVE_PRETTY_PRINT); + options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, 2); + options.put(XmlOptions.SAVE_AGGRESSIVE_NAMESPACES); + String result = object.xmlText(options); + return result; + } + + Random _picker = new Random(1); + + /** + * Cursor position + * Before: + * <theElement>^</theElement> + * After: + * <theElement><lots of stuff/>^</theElement> + */ + private void createSampleForType(SchemaType stype, XmlCursor xmlc) { + if (_typeStack.contains(stype)) + //if ( !flag ) + return; + //else + // flag = false; + + _typeStack.add(stype); + + try { + if (stype.isSimpleType() || stype.isURType()) { + processSimpleType(stype, xmlc); + return; + } + + // complex Type + // <theElement>^</theElement> + processAttributes(stype, xmlc); + + // <theElement attri1="string">^</theElement> + switch (stype.getContentType()) { + case SchemaType.NOT_COMPLEX_TYPE: + case SchemaType.EMPTY_CONTENT: + // noop + break; + case SchemaType.SIMPLE_CONTENT: { + processSimpleType(stype, xmlc); + } + break; + case SchemaType.MIXED_CONTENT: + if (isGenerate_sample_data()) + xmlc.insertChars(pick(WORDS) + " "); + if (stype.getContentModel() != null) { + processParticle(stype.getContentModel(), xmlc, true); + } + if (isGenerate_sample_data()) + xmlc.insertChars(pick(WORDS)); + + break; + case SchemaType.ELEMENT_CONTENT: + if (stype.getContentModel() != null) { + processParticle(stype.getContentModel(), xmlc, false); + } + break; + } + } finally { + _typeStack.remove(_typeStack.size() - 1); + } + } + + private void processSimpleType(SchemaType stype, XmlCursor xmlc) { + String sample = sampleDataForSimpleType(stype); + xmlc.insertChars(sample); + + } + + private String sampleDataForSimpleType(SchemaType sType) { + if (isGenerate_sample_data()) { + return generateSampleDataForSimpleType(sType); + } else { + return BLANK_STRING; + } + } + + private String generateSampleDataForSimpleType(SchemaType sType) { + if (XmlObject.type.equals(sType)) + return "anyType"; + + if (XmlAnySimpleType.type.equals(sType)) + return "anySimpleType"; + + if (sType.getSimpleVariety() == SchemaType.LIST) { + SchemaType itemType = sType.getListItemType(); + StringBuffer sb = new StringBuffer(); + int length = pickLength(sType); + if (length > 0) + sb.append(sampleDataForSimpleType(itemType)); + for (int i = 1; i < length; i += 1) { + sb.append(' '); + sb.append(sampleDataForSimpleType(itemType)); + } + return sb.toString(); + } + + if (sType.getSimpleVariety() == SchemaType.UNION) { + SchemaType[] possibleTypes = sType.getUnionConstituentTypes(); + if (possibleTypes.length == 0) + return ""; + return sampleDataForSimpleType(possibleTypes[pick(possibleTypes.length)]); + } + + XmlAnySimpleType[] enumValues = sType.getEnumerationValues(); + if (enumValues != null && enumValues.length > 0) { + return enumValues[pick(enumValues.length)].getStringValue(); + } + + switch (sType.getPrimitiveType().getBuiltinTypeCode()) { + default: + case SchemaType.BTC_NOT_BUILTIN: + return ""; + + case SchemaType.BTC_ANY_TYPE: + case SchemaType.BTC_ANY_SIMPLE: + return "anything"; + + case SchemaType.BTC_BOOLEAN: + return pick(2) == 0 ? "true" : "false"; + + case SchemaType.BTC_BASE_64_BINARY: { + String result = null; + try { + result = new String(Base64.encode(formatToLength(pick(WORDS), sType).getBytes("utf-8"))); + } catch (java.io.UnsupportedEncodingException e) { /* Can't possibly happen */ + } + return result; + } + + case SchemaType.BTC_HEX_BINARY: + return HexBin.encode(formatToLength(pick(WORDS), sType)); + + case SchemaType.BTC_ANY_URI: + return formatToLength("http://www." + pick(DNS1) + "." + pick(DNS2) + "/" + pick(WORDS) + "/" + pick(WORDS), sType); + + case SchemaType.BTC_QNAME: + return formatToLength("qname", sType); + + case SchemaType.BTC_NOTATION: + return formatToLength("notation", sType); + + case SchemaType.BTC_FLOAT: + return "1.5E2"; + case SchemaType.BTC_DOUBLE: + return "1.051732E7"; + case SchemaType.BTC_DECIMAL: + switch (closestBuiltin(sType).getBuiltinTypeCode()) { + case SchemaType.BTC_SHORT: + return formatDecimal("1", sType); + case SchemaType.BTC_UNSIGNED_SHORT: + return formatDecimal("5", sType); + case SchemaType.BTC_BYTE: + return formatDecimal("2", sType); + case SchemaType.BTC_UNSIGNED_BYTE: + return formatDecimal("6", sType); + case SchemaType.BTC_INT: + return formatDecimal("3", sType); + case SchemaType.BTC_UNSIGNED_INT: + return formatDecimal("7", sType); + case SchemaType.BTC_LONG: + return formatDecimal("10", sType); + case SchemaType.BTC_UNSIGNED_LONG: + return formatDecimal("11", sType); + case SchemaType.BTC_INTEGER: + return formatDecimal("100", sType); + case SchemaType.BTC_NON_POSITIVE_INTEGER: + return formatDecimal("-200", sType); + case SchemaType.BTC_NEGATIVE_INTEGER: + return formatDecimal("-201", sType); + case SchemaType.BTC_NON_NEGATIVE_INTEGER: + return formatDecimal("200", sType); + case SchemaType.BTC_POSITIVE_INTEGER: + return formatDecimal("201", sType); + default: + case SchemaType.BTC_DECIMAL: + return formatDecimal("1000.00", sType); + } + + case SchemaType.BTC_STRING: { + String result; + switch (closestBuiltin(sType).getBuiltinTypeCode()) { + case SchemaType.BTC_STRING: + case SchemaType.BTC_NORMALIZED_STRING: + result = "string"; + break; + + case SchemaType.BTC_TOKEN: + result = "token"; + break; + + default: + result = "string"; + break; + } + + return formatToLength(result, sType); + } + + case SchemaType.BTC_DURATION: + return formatDuration(sType); + + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + return formatDate(sType); + } + } + + // a bit from the Aenid + public static final String[] WORDS = new String[] { "ipsa", "iovis", "rapidum", "iaculata", "e", "nubibus", "ignem", "disiecitque", "rates", + "evertitque", "aequora", "ventis", "illum", "exspirantem", "transfixo", "pectore", "flammas", "turbine", "corripuit", "scopuloque", + "infixit", "acuto", "ast", "ego", "quae", "divum", "incedo", "regina", "iovisque", "et", "soror", "et", "coniunx", "una", "cum", "gente", + "tot", "annos", "bella", "gero", "et", "quisquam", "numen", "iunonis", "adorat", "praeterea", "aut", "supplex", "aris", "imponet", + "honorem", "talia", "flammato", "secum", "dea", "corde", "volutans", "nimborum", "in", "patriam", "loca", "feta", "furentibus", + "austris", "aeoliam", "venit", "hic", "vasto", "rex", "aeolus", "antro", "luctantis", "ventos", "tempestatesque", "sonoras", "imperio", + "premit", "ac", "vinclis", "et", "carcere", "frenat", "illi", "indignantes", "magno", "cum", "murmure", "montis", "circum", "claustra", + "fremunt", "celsa", "sedet", "aeolus", "arce", "sceptra", "tenens", "mollitque", "animos", "et", "temperat", "iras", "ni", "faciat", + "maria", "ac", "terras", "caelumque", "profundum", "quippe", "ferant", "rapidi", "secum", "verrantque", "per", "auras", "sed", "pater", + "omnipotens", "speluncis", "abdidit", "atris", "hoc", "metuens", "molemque", "et", "montis", "insuper", "altos", "imposuit", "regemque", + "dedit", "qui", "foedere", "certo", "et", "premere", "et", "laxas", "sciret", "dare", "iussus", "habenas", }; + + private static final String[] DNS1 = new String[] { "corp", "your", "my", "sample", "company", "test", "any" }; + + private static final String[] DNS2 = new String[] { "com", "org", "com", "gov", "org", "com", "org", "com", "edu" }; + + private int pick(int n) { + return _picker.nextInt(n); + } + + private String pick(String[] a) { + return a[pick(a.length)]; + } + + private String pick(String[] a, int count) { + if (count <= 0) + return ""; + + int i = pick(a.length); + StringBuffer sb = new StringBuffer(a[i]); + while (count-- > 0) { + i += 1; + if (i >= a.length) + i = 0; + sb.append(' '); + sb.append(a[i]); + } + return sb.toString(); + } + + private String pickDigits(int digits) { + StringBuffer sb = new StringBuffer(); + while (digits-- > 0) + sb.append(Integer.toString(pick(10))); + return sb.toString(); + } + + private int pickLength(SchemaType sType) { + XmlInteger length = (XmlInteger) sType.getFacet(SchemaType.FACET_LENGTH); + if (length != null) + return length.getBigIntegerValue().intValue(); + XmlInteger min = (XmlInteger) sType.getFacet(SchemaType.FACET_MIN_LENGTH); + XmlInteger max = (XmlInteger) sType.getFacet(SchemaType.FACET_MAX_LENGTH); + int minInt, maxInt; + if (min == null) + minInt = 0; + else + minInt = min.getBigIntegerValue().intValue(); + if (max == null) + maxInt = Integer.MAX_VALUE; + else + maxInt = max.getBigIntegerValue().intValue(); + // We try to keep the length of the array within reasonable limits, + // at least 1 item and at most 3 if possible + if (minInt == 0 && maxInt >= 1) + minInt = 1; + if (maxInt > minInt + 2) + maxInt = minInt + 2; + if (maxInt < minInt) + maxInt = minInt; + return minInt + pick(maxInt - minInt); + } + + /** + * Formats a given string to the required length, using the following operations: + * - append the source string to itself as necessary to pass the minLength; + * - truncate the result of previous step, if necessary, to keep it within minLength. + */ + private String formatToLength(String s, SchemaType sType) { + String result = s; + try { + SimpleValue min = (SimpleValue) sType.getFacet(SchemaType.FACET_LENGTH); + if (min == null) + min = (SimpleValue) sType.getFacet(SchemaType.FACET_MIN_LENGTH); + if (min != null) { + int len = min.getIntValue(); + while (result.length() < len) + result = result + result; + } + SimpleValue max = (SimpleValue) sType.getFacet(SchemaType.FACET_LENGTH); + if (max == null) + max = (SimpleValue) sType.getFacet(SchemaType.FACET_MAX_LENGTH); + if (max != null) { + int len = max.getIntValue(); + if (result.length() > len) + result = result.substring(0, len); + } + } catch (Exception e) // intValue can be out of range + { + } + return result; + } + + private String formatDecimal(String start, SchemaType sType) { + BigDecimal result = new BigDecimal(start); + XmlDecimal xmlD; + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null; + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null; + boolean minInclusive = true, maxInclusive = true; + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (xmlD != null) { + BigDecimal minExcl = xmlD.getBigDecimalValue(); + if (min == null || min.compareTo(minExcl) < 0) { + min = minExcl; + minInclusive = false; + } + } + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (xmlD != null) { + BigDecimal maxExcl = xmlD.getBigDecimalValue(); + if (max == null || max.compareTo(maxExcl) > 0) { + max = maxExcl; + maxInclusive = false; + } + } + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); + int totalDigits = -1; + if (xmlD != null) { + totalDigits = xmlD.getBigDecimalValue().intValue(); + + StringBuffer sb = new StringBuffer(totalDigits); + for (int i = 0; i < totalDigits; i++) + sb.append('9'); + BigDecimal digitsLimit = new BigDecimal(sb.toString()); + if (max != null && max.compareTo(digitsLimit) > 0) { + max = digitsLimit; + maxInclusive = true; + } + digitsLimit = digitsLimit.negate(); + if (min != null && min.compareTo(digitsLimit) < 0) { + min = digitsLimit; + minInclusive = true; + } + } + + int sigMin = min == null ? 1 : result.compareTo(min); + int sigMax = max == null ? -1 : result.compareTo(max); + boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive; + boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive; + + // Compute the minimum increment + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS); + int fractionDigits = -1; + BigDecimal increment; + if (xmlD == null) + increment = new BigDecimal(1); + else { + fractionDigits = xmlD.getBigDecimalValue().intValue(); + if (fractionDigits > 0) { + StringBuffer sb = new StringBuffer("0."); + for (int i = 1; i < fractionDigits; i++) + sb.append('0'); + sb.append('1'); + increment = new BigDecimal(sb.toString()); + } else + increment = new BigDecimal(1.0); + } + + if (minOk && maxOk) { + // OK + } else if (minOk && !maxOk) { + // TOO BIG + if (maxInclusive) + result = max; + else + result = max.subtract(increment); + } else if (!minOk && maxOk) { + // TOO SMALL + if (minInclusive) + result = min; + else + result = min.add(increment); + } else { + // MIN > MAX!! + } + + // We have the number + // Adjust the scale according to the totalDigits and fractionDigits + int digits = 0; + BigDecimal ONE = new BigDecimal(BigInteger.ONE); + for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++) + n = n.movePointLeft(1); + + if (fractionDigits > 0) + if (totalDigits >= 0) + result.setScale(Math.max(fractionDigits, totalDigits - digits)); + else + result.setScale(fractionDigits); + else if (fractionDigits == 0) + result.setScale(0); + + return result.toString(); + } + + private String formatDuration(SchemaType sType) { + XmlDuration d = (XmlDuration) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + GDuration minInclusive = null; + if (d != null) + minInclusive = d.getGDurationValue(); + + d = (XmlDuration) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + GDuration maxInclusive = null; + if (d != null) + maxInclusive = d.getGDurationValue(); + + d = (XmlDuration) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + GDuration minExclusive = null; + if (d != null) + minExclusive = d.getGDurationValue(); + + d = (XmlDuration) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + GDuration maxExclusive = null; + if (d != null) + maxExclusive = d.getGDurationValue(); + + GDurationBuilder gdurb = new GDurationBuilder(); + BigInteger min, max; + + gdurb.setSecond(pick(800000)); + gdurb.setMonth(pick(20)); + + // Years + // Months + // Days + // Hours + // Minutes + // Seconds + // Fractions + if (minInclusive != null) { + if (gdurb.getYear() < minInclusive.getYear()) + gdurb.setYear(minInclusive.getYear()); + if (gdurb.getMonth() < minInclusive.getMonth()) + gdurb.setMonth(minInclusive.getMonth()); + if (gdurb.getDay() < minInclusive.getDay()) + gdurb.setDay(minInclusive.getDay()); + if (gdurb.getHour() < minInclusive.getHour()) + gdurb.setHour(minInclusive.getHour()); + if (gdurb.getMinute() < minInclusive.getMinute()) + gdurb.setMinute(minInclusive.getMinute()); + if (gdurb.getSecond() < minInclusive.getSecond()) + gdurb.setSecond(minInclusive.getSecond()); + if (gdurb.getFraction().compareTo(minInclusive.getFraction()) < 0) + gdurb.setFraction(minInclusive.getFraction()); + } + + if (maxInclusive != null) { + if (gdurb.getYear() > maxInclusive.getYear()) + gdurb.setYear(maxInclusive.getYear()); + if (gdurb.getMonth() > maxInclusive.getMonth()) + gdurb.setMonth(maxInclusive.getMonth()); + if (gdurb.getDay() > maxInclusive.getDay()) + gdurb.setDay(maxInclusive.getDay()); + if (gdurb.getHour() > maxInclusive.getHour()) + gdurb.setHour(maxInclusive.getHour()); + if (gdurb.getMinute() > maxInclusive.getMinute()) + gdurb.setMinute(maxInclusive.getMinute()); + if (gdurb.getSecond() > maxInclusive.getSecond()) + gdurb.setSecond(maxInclusive.getSecond()); + if (gdurb.getFraction().compareTo(maxInclusive.getFraction()) > 0) + gdurb.setFraction(maxInclusive.getFraction()); + } + + if (minExclusive != null) { + if (gdurb.getYear() <= minExclusive.getYear()) + gdurb.setYear(minExclusive.getYear() + 1); + if (gdurb.getMonth() <= minExclusive.getMonth()) + gdurb.setMonth(minExclusive.getMonth() + 1); + if (gdurb.getDay() <= minExclusive.getDay()) + gdurb.setDay(minExclusive.getDay() + 1); + if (gdurb.getHour() <= minExclusive.getHour()) + gdurb.setHour(minExclusive.getHour() + 1); + if (gdurb.getMinute() <= minExclusive.getMinute()) + gdurb.setMinute(minExclusive.getMinute() + 1); + if (gdurb.getSecond() <= minExclusive.getSecond()) + gdurb.setSecond(minExclusive.getSecond() + 1); + if (gdurb.getFraction().compareTo(minExclusive.getFraction()) <= 0) + gdurb.setFraction(minExclusive.getFraction().add(new BigDecimal(0.001))); + } + + if (maxExclusive != null) { + if (gdurb.getYear() > maxExclusive.getYear()) + gdurb.setYear(maxExclusive.getYear()); + if (gdurb.getMonth() > maxExclusive.getMonth()) + gdurb.setMonth(maxExclusive.getMonth()); + if (gdurb.getDay() > maxExclusive.getDay()) + gdurb.setDay(maxExclusive.getDay()); + if (gdurb.getHour() > maxExclusive.getHour()) + gdurb.setHour(maxExclusive.getHour()); + if (gdurb.getMinute() > maxExclusive.getMinute()) + gdurb.setMinute(maxExclusive.getMinute()); + if (gdurb.getSecond() > maxExclusive.getSecond()) + gdurb.setSecond(maxExclusive.getSecond()); + if (gdurb.getFraction().compareTo(maxExclusive.getFraction()) > 0) + gdurb.setFraction(maxExclusive.getFraction()); + } + + gdurb.normalize(); + return gdurb.toString(); + } + + private String formatDate(SchemaType sType) { + GDateBuilder gdateb = new GDateBuilder(new Date(1000L * pick(365 * 24 * 60 * 60) + (30L + pick(20)) * 365 * 24 * 60 * 60 * 1000)); + GDate min = null, max = null; + GDate temp; + + // Find the min and the max according to the type + switch (sType.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_DATE_TIME: { + XmlDateTime x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) + min = x.getGDateValue(); + x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) + min = x.getGDateValue(); + + x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) + max = x.getGDateValue(); + x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) + max = x.getGDateValue(); + break; + } + case SchemaType.BTC_TIME: { + XmlTime x = (XmlTime) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) + min = x.getGDateValue(); + x = (XmlTime) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) + min = x.getGDateValue(); + + x = (XmlTime) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) + max = x.getGDateValue(); + x = (XmlTime) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) + max = x.getGDateValue(); + break; + } + case SchemaType.BTC_DATE: { + XmlDate x = (XmlDate) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) + min = x.getGDateValue(); + x = (XmlDate) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) + min = x.getGDateValue(); + + x = (XmlDate) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) + max = x.getGDateValue(); + x = (XmlDate) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) + max = x.getGDateValue(); + break; + } + case SchemaType.BTC_G_YEAR_MONTH: { + XmlGYearMonth x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) + min = x.getGDateValue(); + x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) + min = x.getGDateValue(); + + x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) + max = x.getGDateValue(); + x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) + max = x.getGDateValue(); + break; + } + case SchemaType.BTC_G_YEAR: { + XmlGYear x = (XmlGYear) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) + min = x.getGDateValue(); + x = (XmlGYear) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) + min = x.getGDateValue(); + + x = (XmlGYear) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) + max = x.getGDateValue(); + x = (XmlGYear) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) + max = x.getGDateValue(); + break; + } + case SchemaType.BTC_G_MONTH_DAY: { + XmlGMonthDay x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) + min = x.getGDateValue(); + x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) + min = x.getGDateValue(); + + x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) + max = x.getGDateValue(); + x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) + max = x.getGDateValue(); + break; + } + case SchemaType.BTC_G_DAY: { + XmlGDay x = (XmlGDay) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) + min = x.getGDateValue(); + x = (XmlGDay) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) + min = x.getGDateValue(); + + x = (XmlGDay) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) + max = x.getGDateValue(); + x = (XmlGDay) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) + max = x.getGDateValue(); + break; + } + case SchemaType.BTC_G_MONTH: { + XmlGMonth x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) + min = x.getGDateValue(); + x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) + min = x.getGDateValue(); + + x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) + max = x.getGDateValue(); + x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) + max = x.getGDateValue(); + break; + } + } + + if (min != null && max == null) { + if (min.compareToGDate(gdateb) >= 0) { + // Reset the date to min + (1-8) hours + Calendar c = gdateb.getCalendar(); + c.add(Calendar.HOUR_OF_DAY, pick(8)); + gdateb = new GDateBuilder(c); + } + } else if (min == null && max != null) { + if (max.compareToGDate(gdateb) <= 0) { + // Reset the date to max - (1-8) hours + Calendar c = gdateb.getCalendar(); + c.add(Calendar.HOUR_OF_DAY, 0 - pick(8)); + gdateb = new GDateBuilder(c); + } + } else if (min != null && max != null) { + if (min.compareToGDate(gdateb) >= 0 || max.compareToGDate(gdateb) <= 0) { + // Find a date between the two + Calendar c = min.getCalendar(); + Calendar cmax = max.getCalendar(); + c.add(Calendar.HOUR_OF_DAY, 1); + if (c.after(cmax)) { + c.add(Calendar.HOUR_OF_DAY, -1); + c.add(Calendar.MINUTE, 1); + if (c.after(cmax)) { + c.add(Calendar.MINUTE, -1); + c.add(Calendar.SECOND, 1); + if (c.after(cmax)) { + c.add(Calendar.SECOND, -1); + c.add(Calendar.MILLISECOND, 1); + if (c.after(cmax)) + c.add(Calendar.MILLISECOND, -1); + } + } + } + gdateb = new GDateBuilder(c); + } + } + + gdateb.setBuiltinTypeCode(sType.getPrimitiveType().getBuiltinTypeCode()); + if (pick(2) == 0) + gdateb.clearTimeZone(); + return gdateb.toString(); + } + + private SchemaType closestBuiltin(SchemaType sType) { + while (!sType.isBuiltinType()) + sType = sType.getBaseType(); + return sType; + } + + /** + * Cracks a combined QName of the form URL:localname + */ + public static QName crackQName(String qName) { + String ns; + String name; + + int index = qName.lastIndexOf(':'); + if (index >= 0) { + ns = qName.substring(0, index); + name = qName.substring(index + 1); + } else { + ns = ""; + name = qName; + } + + return new QName(ns, name); + } + + /** + * Cursor position: + * Before this call: + * <outer><foo/>^</outer> (cursor at the ^) + * After this call: + * <<outer><foo/><bar/>som text<etc/>^</outer> + */ + private void processParticle(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + int loop = determineMinMaxForSample(sp, xmlc); + + while (loop-- > 0) { + switch (sp.getParticleType()) { + case (SchemaParticle.ELEMENT): + processElement(sp, xmlc, mixed); + break; + case (SchemaParticle.SEQUENCE): + processSequence(sp, xmlc, mixed); + break; + case (SchemaParticle.CHOICE): + processChoice(sp, xmlc, mixed); + break; + case (SchemaParticle.ALL): + processAll(sp, xmlc, mixed); + break; + case (SchemaParticle.WILDCARD): + processWildCard(sp, xmlc, mixed); + break; + default: + // throw new Exception("No Match on Schema Particle Type: " + String.valueOf(sp.getParticleType())); + } + } + } + + private int determineMinMaxForSample(SchemaParticle sp, XmlCursor xmlc) { + int minOccurs = sp.getIntMinOccurs(); + int maxOccurs = sp.getIntMaxOccurs(); + + if (minOccurs == maxOccurs) + return minOccurs; + + int result = minOccurs; + if (result == 0 && _nElements < MAX_ELEMENTS) + result = 1; + + if (sp.getParticleType() != SchemaParticle.ELEMENT) + return result; + + // it probably only makes sense to put comments in front of individual elements that repeat + + if (sp.getMaxOccurs() == null) { + // xmlc.insertComment("The next " + getItemNameOrType(sp, xmlc) + " may be repeated " + minOccurs + " or more times"); + if (minOccurs == 0) + xmlc.insertComment("Zero or more repetitions:"); + else + xmlc.insertComment(minOccurs + " or more repetitions:"); + } else if (sp.getIntMaxOccurs() > 1) { + xmlc.insertComment(minOccurs + " to " + String.valueOf(sp.getMaxOccurs()) + " repetitions:"); + } else { + xmlc.insertComment("Optional:"); + } + return result; + } + + /* + Return a name for the element or the particle type to use in the comment for minoccurs, max occurs + */ + private String getItemNameOrType(SchemaParticle sp, XmlCursor xmlc) { + String elementOrTypeName = null; + if (sp.getParticleType() == SchemaParticle.ELEMENT) { + elementOrTypeName = "Element (" + sp.getName().getLocalPart() + ")"; + } else { + elementOrTypeName = printParticleType(sp.getParticleType()); + } + return elementOrTypeName; + } + + private void processElement(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + // cast as schema local element + SchemaLocalElement element = (SchemaLocalElement) sp; + /// ^ -> <elemenname></elem>^ + if (_soapEnc) + xmlc.insertElement(element.getName().getLocalPart()); // soap encoded? drop namespaces. + else + xmlc.insertElement(element.getName().getLocalPart(), element.getName().getNamespaceURI()); + _nElements++; + /// -> <elem>^</elem> + xmlc.toPrevToken(); + // -> <elem>stuff^</elem> + createSampleForType(element.getType(), xmlc); + // -> <elem>stuff</elem>^ + xmlc.toNextToken(); + + } + + private void moveToken(int numToMove, XmlCursor xmlc) { + for (int i = 0; i < Math.abs(numToMove); i++) { + if (numToMove < 0) { + xmlc.toPrevToken(); + } else { + xmlc.toNextToken(); + } + } + } + + private static final String formatQName(XmlCursor xmlc, QName qName) { + XmlCursor parent = xmlc.newCursor(); + parent.toParent(); + String prefix = parent.prefixForNamespace(qName.getNamespaceURI()); + parent.dispose(); + String name; + if (prefix == null || prefix.length() == 0) + name = qName.getLocalPart(); + else + name = prefix + ":" + qName.getLocalPart(); + return name; + } + + private static final QName HREF = new QName("href"); + + private static final QName ID = new QName("id"); + + private static final QName XSI_TYPE = new QName("http://www.w3.org/2001/XMLSchema-instance", "type"); + + private static final QName ENC_ARRAYTYPE = new QName("http://schemas.xmlsoap.org/soap/encoding/", "arrayType"); + + private static final QName ENC_OFFSET = new QName("http://schemas.xmlsoap.org/soap/encoding/", "offset"); + + private static final Set SKIPPED_SOAP_ATTRS = new HashSet(Arrays.asList(new QName[] { HREF, ID, ENC_OFFSET })); + + private void processAttributes(SchemaType stype, XmlCursor xmlc) { + if (_soapEnc) { + QName typeName = stype.getName(); + if (typeName != null) { + xmlc.insertAttributeWithValue(XSI_TYPE, formatQName(xmlc, typeName)); + } + } + + SchemaProperty[] attrProps = stype.getAttributeProperties(); + for (int i = 0; i < attrProps.length; i++) { + SchemaProperty attr = attrProps[i]; + if (_soapEnc) { + if (SKIPPED_SOAP_ATTRS.contains(attr.getName())) + continue; + if (ENC_ARRAYTYPE.equals(attr.getName())) { + SOAPArrayType arrayType = ((SchemaWSDLArrayType) stype.getAttributeModel().getAttribute(attr.getName())).getWSDLArrayType(); + if (arrayType != null) + xmlc.insertAttributeWithValue(attr.getName(), formatQName(xmlc, arrayType.getQName()) + arrayType.soap11DimensionString()); + continue; + } + } + String defaultValue = attr.getDefaultText(); + xmlc.insertAttributeWithValue(attr.getName(), defaultValue == null ? sampleDataForSimpleType(attr.getType()) : defaultValue); + } + } + + private void processSequence(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + SchemaParticle[] spc = sp.getParticleChildren(); + for (int i = 0; i < spc.length; i++) { + /// <parent>maybestuff^</parent> + processParticle(spc[i], xmlc, mixed); + //<parent>maybestuff...morestuff^</parent> + if (mixed && i < spc.length - 1) { + if (isGenerate_sample_data()) { + xmlc.insertChars(pick(WORDS)); + } else { + xmlc.insertChars(""); + } + } + } + } + + private void processChoice(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + SchemaParticle[] spc = sp.getParticleChildren(); + xmlc.insertComment("You have a CHOICE of the next " + String.valueOf(spc.length) + " items at this level"); + for (int i = 0; i < spc.length; i++) { + processParticle(spc[i], xmlc, mixed); + } + } + + private void processAll(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + SchemaParticle[] spc = sp.getParticleChildren(); + // xmlc.insertComment("You may enter the following " + String.valueOf(spc.length) + " items in any order"); + for (int i = 0; i < spc.length; i++) { + processParticle(spc[i], xmlc, mixed); + if (mixed && i < spc.length - 1) + xmlc.insertChars(pick(WORDS)); + } + } + + private void processWildCard(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + xmlc.insertComment("You may enter ANY elements at this point"); + xmlc.insertElement("AnyElement"); + } + + /** + * This method will get the base type for the schema type + */ + + private static QName getClosestName(SchemaType sType) { + while (sType.getName() == null) + sType = sType.getBaseType(); + + return sType.getName(); + } + + private String printParticleType(int particleType) { + StringBuffer returnParticleType = new StringBuffer(); + returnParticleType.append("Schema Particle Type: "); + + switch (particleType) { + case SchemaParticle.ALL: + returnParticleType.append("ALL\n"); + break; + case SchemaParticle.CHOICE: + returnParticleType.append("CHOICE\n"); + break; + case SchemaParticle.ELEMENT: + returnParticleType.append("ELEMENT\n"); + break; + case SchemaParticle.SEQUENCE: + returnParticleType.append("SEQUENCE\n"); + break; + case SchemaParticle.WILDCARD: + returnParticleType.append("WILDCARD\n"); + break; + default: + returnParticleType.append("Schema Particle Type Unknown"); + break; + } + + return returnParticleType.toString(); + } + + private ArrayList _typeStack = new ArrayList(); + + public boolean isGenerate_sample_data() { + return generate_sample_data; + } + + public void setGenerate_sample_data(boolean generate_sample_data) { + this.generate_sample_data = generate_sample_data; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XBbasedXMLGenerator.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XBbasedXMLGenerator.java new file mode 100644 index 0000000000..128d65cecd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XBbasedXMLGenerator.java @@ -0,0 +1,253 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript.utils.xmlfromxsd; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; + +import javax.wsdl.Definition; +import javax.wsdl.WSDLException; +import javax.wsdl.extensions.schema.Schema; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +import org.apache.xmlbeans.SchemaGlobalElement; +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.SchemaTypeSystem; +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator; +import org.xml.sax.InputSource; + +import com.ibm.wsdl.util.xml.DOM2Writer; + +public class XBbasedXMLGenerator extends SchemaInstanceGenerator implements XMLGenerator { + private XMLfromXSDConfiguration config = null; + + public static final String QNAME_SEPARATOR = "#"; + + public XBbasedXMLGenerator(XMLfromXSDConfiguration config) { + this.config = config; + // config.setXsdInputStream(getClass().getResource(conf).openStream()); + } + + public Hashtable<String, XmlObject> generateXmlAll() throws Exception { + Hashtable<String, XmlObject> xmlInstances = new Hashtable<String, XmlObject>(); + TuscanySampleXmlUtil xmlUtil = new TuscanySampleXmlUtil(); + xmlUtil.setGenerate_sample_data(config.isGenerateSampleData()); + SchemaTypeSystem sts = processXSDSources(); + SchemaType elementType = null; + for (SchemaGlobalElement globalElement : sts.globalElements()) { + elementType = getRootElementSchemaType(sts, globalElement.getName().getNamespaceURI(), globalElement.getName().getLocalPart()); + xmlInstances.put(makeQName(globalElement.getName()), XmlObject.Factory.parse(xmlUtil.createSampleForType(elementType))); + } + + return xmlInstances; + } + + public String generateXMLAsString() throws Exception { + SchemaTypeSystem sts = processXSDSources(); + SchemaType rootElementType = getRootElementSchemaType(sts, config.getSchemaTypeNamespaceURI(), config.getSchemaTypeName()); + String result = ""; + if (rootElementType != null) { + TuscanySampleXmlUtil xmlUtil = new TuscanySampleXmlUtil(); + xmlUtil.setGenerate_sample_data(config.isGenerateSampleData()); + result = xmlUtil.createSampleForType(rootElementType); + } else { + System.out.println("Could not find a global element with name \"" + config.getRootElementLocalName() + "\""); + } + return result; + } + + public void generateXMLIntoOutputStream() throws Exception { + config.getXmlOutputStream().write(generateXMLAsString().getBytes()); + } + + public void generateXML() throws Exception { + SchemaTypeSystem sts = processXSDSources(); + + SchemaType rootElementType = getRootElementSchemaType(sts, config.getSchemaTypeNamespaceURI(), config.getSchemaTypeName()); + + if (rootElementType != null) { + TuscanySampleXmlUtil xmlUtil = new TuscanySampleXmlUtil(); + xmlUtil.setGenerate_sample_data(config.isGenerateSampleData()); + String result = xmlUtil.createSampleForType(rootElementType); + config.getXmlOutputStream().write(result.getBytes()); + // System.out.println(result); + } else { + System.out.println("Could not find a global element with name \"" + config.getRootElementLocalName() + "\""); + } + } + + protected SchemaType getRootElementSchemaType(SchemaTypeSystem sts, String schemaNamespace, String schemaTypeName) { + SchemaType schemaType = null; + + if (sts == null) { + System.out.println("No Schemas to process."); + } else { + // first check in the global types + SchemaType[] globalTypes = sts.globalTypes(); + for (int i = 0; i < globalTypes.length; i++) { + if (schemaNamespace.equals(globalTypes[i].getName().getNamespaceURI()) + && schemaTypeName.equals(globalTypes[i].getName().getLocalPart())) { + schemaType = globalTypes[i]; + break; + } + } + + // next check for anonymous types defined inline within elements + if (schemaType == null) { + SchemaType[] globalElems = sts.documentTypes(); + for (int i = 0; i < globalElems.length; i++) { + if (schemaNamespace.equals(globalElems[i].getDocumentElementName().getNamespaceURI()) + && schemaTypeName.equals(globalElems[i].getDocumentElementName().getLocalPart())) { + schemaType = globalElems[i]; + break; + } + } + } + } + return schemaType; + } + + public void generateXML(XMLfromXSDConfiguration config) throws Exception { + this.config = config; + generateXML(); + } + + public XMLfromXSDConfiguration getConfig() { + return config; + } + + public void setConfig(XMLfromXSDConfiguration config) { + this.config = config; + } + + private Definition readInTheWSDLFile(InputStream wsdlStream) throws WSDLException { + WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); + reader.setFeature("javax.wsdl.importDocuments", true); + + /* + * File file = new File(uri); String baseURI; + * + * if (uri.startsWith("http://")){ baseURI = uri; } else{ if(file.getParentFile() == null){ try { baseURI = new + * File(".").getCanonicalFile().toURI().toString(); } catch (IOException e) { throw new RuntimeException(e); } } else { baseURI = + * file.getParentFile().toURI().toString(); } } + */ + // Document doc; + InputSource inputSource; + try { + + // doc = XMLUtils.newDocument(wsdlStream); + inputSource = new InputSource(wsdlStream); + /* + * } catch (ParserConfigurationException e) { throw new WSDLException(WSDLException.PARSER_ERROR, "Parser Configuration Error", e); } + * catch (SAXException e) { throw new WSDLException(WSDLException.PARSER_ERROR, "Parser SAX Error", e); + */ + } catch (Exception e) { + throw new WSDLException(WSDLException.INVALID_WSDL, "IO Error", e); + } + + // return reader.readWSDL(config.getRootElementNamespaceURI(), doc); + return reader.readWSDL(config.getRootElementNamespaceURI(), inputSource); + } + + protected InputStream[] getXSDsFromWSDL(InputStream xsdInputStream) throws Exception { + Definition defn = readInTheWSDLFile(xsdInputStream); + List list = defn.getTypes().getExtensibilityElements(); + + InputStream[] xsdFragments = new InputStream[list.size()]; + + Iterator iterator = list.iterator(); + Schema schemaElement = null; + + for (int count = 0; count < list.size(); ++count) { + schemaElement = (Schema) iterator.next(); + // System.out.println(" *** - " + element.getElementType().getNamespaceURI()); + // System.out.println(" **** - " + element + " & " + element.getClass().getPackage().getName()); + // System.out.println(DOM2Writer.nodeToString(element.getElement())); + xsdFragments[count] = new ByteArrayInputStream(DOM2Writer.nodeToString(schemaElement.getElement()).getBytes()); + } + + return xsdFragments; + } + + protected SchemaTypeSystem processXSDSources() throws Exception { + SchemaTypeSystem sts = null; + if (config.getXsdFileName().endsWith(XSD_FILE)) { + sts = processXSDs(new InputStream[] { config.getXsdInputStream() }); + } else if (config.getXsdFileName().endsWith(WSDL_FILE)) { + sts = processXSDs(getXSDsFromWSDL(config.getXsdInputStream())); + } + return sts; + } + + protected SchemaTypeSystem processXSDs(InputStream[] inputStreams) { + List sdocs = new ArrayList(); + for (int i = 0; i < inputStreams.length; i++) { + try { + sdocs.add(XmlObject.Factory.parse(inputStreams[i], (new XmlOptions()).setLoadLineNumbers().setLoadMessageDigest())); + } catch (Exception e) { + System.err.println("Can not load schema file: " + inputStreams[i] + ": "); + e.printStackTrace(); + } + } + + XmlObject[] schemas = (XmlObject[]) sdocs.toArray(new XmlObject[sdocs.size()]); + + SchemaTypeSystem sts = null; + if (schemas.length > 0) { + Collection errors = new ArrayList(); + XmlOptions compileOptions = new XmlOptions(); + /* + * if (dl) compileOptions.setCompileDownloadUrls(); if (nopvr) compileOptions.setCompileNoPvrRule(); if (noupa) + * compileOptions.setCompileNoUpaRule(); + */ + try { + sts = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), compileOptions); + } catch (Exception e) { + if (errors.isEmpty() || !(e instanceof XmlException)) + e.printStackTrace(); + + System.out.println("Schema compilation errors: "); + for (Iterator i = errors.iterator(); i.hasNext();) + System.out.println(i.next()); + } + } + + return sts; + } + + private String makeQName(String nameSpace, String localName) { + return nameSpace + QNAME_SEPARATOR + localName; + } + + private String makeQName(QName qName) { + return qName.getNamespaceURI() + QNAME_SEPARATOR + qName.getLocalPart(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLGenerator.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLGenerator.java new file mode 100644 index 0000000000..15848158e6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLGenerator.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.container.javascript.utils.xmlfromxsd; + +import java.util.Hashtable; + +import org.apache.xmlbeans.XmlObject; + +/** + * This is the XMLGenerator Interface that will be implemented by various + * types of Generators (SDO based, XMLBeans based etc.) + * + */ +public interface XMLGenerator { + public static final int SDO_BASED = 1; + + public static final int XMLBEANS_BASED = 2; + + public static final String XSD_FILE = ".xsd"; + + public static final String WSDL_FILE = ".wsdl"; + + public void generateXML() throws Exception; + + public void generateXML(XMLfromXSDConfiguration config) throws Exception; + + public void generateXMLIntoOutputStream() throws Exception; + + public String generateXMLAsString() throws Exception; + + public Hashtable<String, XmlObject> generateXmlAll() throws Exception; + + public XMLfromXSDConfiguration getConfig(); + + public void setConfig(XMLfromXSDConfiguration config); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLGeneratorFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLGeneratorFactory.java new file mode 100644 index 0000000000..e4075557e8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLGeneratorFactory.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.container.javascript.utils.xmlfromxsd; + +/** + * This is a factory for creating XML Generators. The types of XML Generators + * are enumerated in the XMLGenerator interface. + * + */ +public class XMLGeneratorFactory { + private static XMLGeneratorFactory factory = null; + + protected XMLGeneratorFactory() { + + } + + public static XMLGeneratorFactory getInstance() { + if (factory == null) { + factory = new XMLGeneratorFactory(); + } + return factory; + } + + public XMLGenerator createGenerator(int generatorType) { + XMLGenerator generator = null; + switch (generatorType) { + case XMLGenerator.SDO_BASED: { + // generator = new SDObasedXMLGenerator(new XMLfromXSDConfiguration()); + break; + } + case XMLGenerator.XMLBEANS_BASED: { + generator = new XBbasedXMLGenerator(new XMLfromXSDConfiguration()); + break; + } + } + + return generator; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDConfiguration.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDConfiguration.java new file mode 100644 index 0000000000..76f6b711bd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDConfiguration.java @@ -0,0 +1,246 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript.utils.xmlfromxsd; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; + +/** + * This class encapsulates the configuration settings for the "XML From XSD" generation. + * Presently it contains settings like the XSD to be use, the schematype for which and + * xml instance is to be created, the destination for the output etc. All of these + * settings are used by the 'generator' classes during the genation of the xml instance. + * + */ +public class XMLfromXSDConfiguration implements CmdLineArgsHandler { + private static int fileCount = 0; + + public static final String DEFAULT_XML_OUTPUT_FILENAME = "XML_FROM_XSD_" + (++fileCount) + ".xml"; + + public static final String XSD_FILE_URL_OPTION = "xsd"; + + public static final String XML_OUTPUT_LOCATION_OPTION = "o"; + + public static final String XML_OUTPUT_FILENAME_OPTION = "of"; + + public static final String ROOT_ELEMENT_NAMESPACE_URI_OPTION = "rns"; + + public static final String ROOT_ELEMENT_LOCALNAME_OPTION = "rn"; + + public static final String SCHEMA_TYPE_NAME = "st"; + + public static final String SCHEMA_TYPE_NAMESPACE_URI = "stn"; + + public static final String GENERATE_SAMPLE_DATA = "sd"; + + protected String xmlOutputLocation = null; + + protected File xmlOutputDirectory = null; + + protected String xsdFileName = null; + + protected String xmlFileName = null; + + protected InputStream xsdInputStream = null; + + protected OutputStream xmlOutputStream = null; + + protected String rootElementNamespaceURI = null; + + protected String rootElementLocalName = null; + + protected String schemaTypeName = null; + + protected String schemaTypeNamespaceURI = null; + + protected boolean generateSampleData = false; + + private void handleXSDInputFileOption(String xsdFileUrl) throws Exception { + xsdFileName = xsdFileUrl; + // xsdInputStream = new FileInputStream(new File(xsdFileName)); + URL resourceUrl = Thread.currentThread().getContextClassLoader().getResource(xsdFileName); + if (resourceUrl != null) { + xsdInputStream = resourceUrl.openStream(); + } else { + File inFile = new File(xsdFileName); + xsdFileName = inFile.getName(); + xsdInputStream = new FileInputStream(inFile); + } + } + + private void handleXMLOutputLocationOption(String outputLocation) throws Exception { + xmlOutputLocation = outputLocation; + xmlOutputDirectory = new File(xmlOutputLocation); + if (!xmlOutputDirectory.exists()) { + xmlOutputDirectory.mkdirs(); + } else if (!xmlOutputDirectory.isDirectory()) { + throw new IllegalArgumentException("The input location for the xml output " + outputLocation + "is not a folder"); + } + } + + private void handleOutputFilenameOption(String outputFileName) throws Exception { + xmlFileName = outputFileName; + + // first create a file in the given location + File outputFile = new File(xmlOutputDirectory, xmlFileName); + + try { + if (!outputFile.exists()) { + outputFile.createNewFile(); + } + xmlOutputStream = new FileOutputStream(outputFile); + } catch (IOException e) { + throw new Exception(e); + } + } + + public void handleArgument(String optionFlag, String argValue) throws IllegalArgumentException { + try { + if (XSD_FILE_URL_OPTION.equalsIgnoreCase(optionFlag)) { + handleXSDInputFileOption(argValue); + } else if (XML_OUTPUT_LOCATION_OPTION.equalsIgnoreCase(optionFlag)) { + handleXMLOutputLocationOption(argValue); + } else if (XML_OUTPUT_FILENAME_OPTION.equalsIgnoreCase(optionFlag)) { + handleOutputFilenameOption(argValue); + } else if (ROOT_ELEMENT_NAMESPACE_URI_OPTION.equalsIgnoreCase(optionFlag)) { + setRootElementNamespaceURI(argValue); + } else if (ROOT_ELEMENT_LOCALNAME_OPTION.equalsIgnoreCase(optionFlag)) { + setRootElementLocalName(argValue); + } else if (SCHEMA_TYPE_NAME.equalsIgnoreCase(optionFlag)) { + setSchemaTypeName(argValue); + } else if (SCHEMA_TYPE_NAMESPACE_URI.equalsIgnoreCase(optionFlag)) { + setSchemaTypeNamespaceURI(argValue); + } else if (GENERATE_SAMPLE_DATA.equalsIgnoreCase(optionFlag)) { + setGenerateSampleData(true); + } + } catch (Exception e) { + throw new IllegalArgumentException("Exception due to - " + e); + } + } + + public String getRootElementLocalName() { + if (rootElementLocalName == null) { + rootElementLocalName = schemaTypeName.toLowerCase(); + } + return rootElementLocalName; + } + + public void setRootElementLocalName(String rootElementLocalName) { + this.rootElementLocalName = rootElementLocalName; + } + + public String getRootElementNamespaceURI() { + if (rootElementNamespaceURI == null) { + rootElementNamespaceURI = schemaTypeNamespaceURI; + } + return rootElementNamespaceURI; + } + + public void setRootElementNamespaceURI(String rootElementNamespaceURI) { + this.rootElementNamespaceURI = rootElementNamespaceURI; + } + + public String getXmlFileName() { + if (xmlFileName == null) { + xmlFileName = getXsdFileName() + ".xml"; + } + return xmlFileName; + } + + public void setXmlFileName(String xmlFileName) { + this.xmlFileName = xmlFileName; + } + + public File getXmlOutputLocation() { + return xmlOutputDirectory; + } + + public void setXmlOutputLocation(File xmlOutputLocation) { + this.xmlOutputDirectory = xmlOutputLocation; + } + + public OutputStream getXmlOutputStream() throws Exception { + if (xmlOutputStream == null) { + if (xmlOutputDirectory == null) { + handleXMLOutputLocationOption(System.getProperty("user.dir")); + } + handleOutputFilenameOption(getXmlFileName()); + } + return xmlOutputStream; + } + + public void setXmlOutputStream(OutputStream xmlOutputStream) { + this.xmlOutputStream = xmlOutputStream; + } + + public String getXsdFileName() { + return xsdFileName; + } + + public void setXsdFileName(String xsdFileName) throws Exception { + this.xsdFileName = xsdFileName; + handleXSDInputFileOption(xsdFileName); + } + + public InputStream getXsdInputStream() throws Exception { + if (xsdInputStream == null) { + throw new IllegalArgumentException("XSD Input Source not set....!"); + } + return xsdInputStream; + } + + public void setXsdInputStream(InputStream xsdInputStream) { + this.xsdInputStream = xsdInputStream; + } + + public String getSchemaTypeName() { + return schemaTypeName; + } + + public void setSchemaTypeName(String schemaTypeName) { + this.schemaTypeName = schemaTypeName; + } + + public String getSchemaTypeNamespaceURI() { + return schemaTypeNamespaceURI; + } + + public void setSchemaTypeNamespaceURI(String schemaTypeNamespaceURI) { + this.schemaTypeNamespaceURI = schemaTypeNamespaceURI; + } + + public void setXmlOutputLocation(String xmlOutputLocation) throws Exception { + this.xmlOutputLocation = xmlOutputLocation; + handleXMLOutputLocationOption(xmlOutputLocation); + } + + public boolean isGenerateSampleData() { + return generateSampleData; + } + + public void setGenerateSampleData(boolean generateSampleData) { + this.generateSampleData = generateSampleData; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDGenerator.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDGenerator.java new file mode 100644 index 0000000000..357d4203fe --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDGenerator.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.container.javascript.utils.xmlfromxsd; + +/** + * This class provides a command line tooling functinality for creating an XML + * instance from an input XSD. + */ +public class XMLfromXSDGenerator { + public static int generatorType = XMLGenerator.XMLBEANS_BASED; + + /** + * @param args + */ + public static void main(String[] args) { + try { + new XMLfromXSDGenerator().generateXMLInstance(args); + } catch (Exception e) { + e.printStackTrace(); + System.out.println(getPrintUsageMessage()); + } + } + + public void generateXMLInstance(String args[]) throws Exception { + // create a configuration object to hold settings for this generation + XMLfromXSDConfiguration config = new XMLfromXSDConfiguration(); + + // create an argument processor to process the input arguments + CmdLineArgsProcessor argsProcessor = new CmdLineArgsProcessor(); + + // configure the args processor with the 'config' object that must be populated + // with values from the proecessed input arguments + argsProcessor.setArgsHandler(config); + + // set the usage message to be output by the args processor if input arguments are not proper + argsProcessor.setPrintUsageMessage(getPrintUsageMessage()); + + // start processing the arguments + argsProcessor.processArgs(args); + + // now that the configuration settings are populated from the input arguments + // instantiate the xmlfromsdogenerator with this config object + + XMLGenerator generator = new XMLGeneratorFactory().createGenerator(generatorType); + // XBbasedXMLGenerator generator = new XBbasedXMLGenerator(config); + + // generate the xml instance + generator.generateXML(config); + } + + protected static String getPrintUsageMessage() { + StringBuffer strBuffer = new StringBuffer(); + strBuffer.append("Usage arguments:\n"); + strBuffer.append(" [ -rns <root element namespace URI> ]\n"); + strBuffer.append(" [ -rn <root element name> ]\n"); + strBuffer.append(" [ -xsd <xsd file> ]\n"); + strBuffer.append(" [ -of <output xml filename> ]\n"); + strBuffer.append(" [ -o <output location> ]\n"); + strBuffer.append(" [ -st <name of the schema type to be instantiated as xml> ]\n"); + strBuffer.append(" [ -stn <namespace URI of the schema type> ]\n"); + strBuffer.append(" [ -sd (provide this flag if sample data is to be generated)\n"); + + return strBuffer.toString(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceCreationException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceCreationException.java new file mode 100644 index 0000000000..140d3efdb4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceCreationException.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.container.javascript.utils.xmlfromxsd; + +/** + * The Exception wrapper class for encasulating exceptions that occur during xml instance creation + * + */ +public class XmlInstanceCreationException extends Exception { + + public XmlInstanceCreationException(String message) { + super(message); + } + + public XmlInstanceCreationException(Exception e) { + super(e); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceRegistry.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceRegistry.java new file mode 100644 index 0000000000..15f0fcfb73 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceRegistry.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript.utils.xmlfromxsd; + +import java.util.Map; + +import org.apache.xmlbeans.XmlObject; + +/** + * Interface for system registry of xml instances + * + */ +public interface XmlInstanceRegistry { + public Map<String, XmlObject> getXmlInstance(String wsdlPath) throws XmlInstanceCreationException; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceRegistryImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceRegistryImpl.java new file mode 100644 index 0000000000..73b7232eae --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XmlInstanceRegistryImpl.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.container.javascript.utils.xmlfromxsd; + +import java.util.Hashtable; +import java.util.Map; + +import org.apache.xmlbeans.XmlObject; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +/** + * An implementation for the XMLInstnaceRegistry + * + */ +@Scope("MODULE") +public class XmlInstanceRegistryImpl implements XmlInstanceRegistry { + + private Hashtable<String, Map<String, XmlObject>> wsdlXmlInstances; + + private XMLGenerator xmlGenerator; + + public XmlInstanceRegistryImpl() { + wsdlXmlInstances = new Hashtable<String, Map<String, XmlObject>>(); + + XMLfromXSDConfiguration generationConfig = new XMLfromXSDConfiguration(); + xmlGenerator = XMLGeneratorFactory.getInstance().createGenerator(XMLGenerator.XMLBEANS_BASED); + xmlGenerator.setConfig(generationConfig); + } + + @Init(eager = true) + public void init() { + } + + /* (non-Javadoc) + * @see org.apache.tuscany.container.javascript.XmlInstanceRegistry#getXmlInstance(java.lang.String, java.lang.String, java.lang.String) + */ + public Map<String, XmlObject> getXmlInstance(String wsdlPath) throws XmlInstanceCreationException { + Map<String, XmlObject> xmlInstanceMap = null; + if ((xmlInstanceMap = wsdlXmlInstances.get(wsdlPath)) == null) { + try { + xmlGenerator.getConfig().setXsdFileName(wsdlPath); + xmlInstanceMap = xmlGenerator.generateXmlAll(); + wsdlXmlInstances.put(wsdlPath, xmlInstanceMap); + } catch (Exception e) { + throw new XmlInstanceCreationException(e); + } + } + return xmlInstanceMap; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..beb51e4c82 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/resources/META-INF/sca/default.scdl @@ -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. +--> +<!-- + JavaScript configuration for the launcher environment. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + + name="org.apache.tuscany.launcher.JavaScriptImplementation"> + + <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <group>org.apache.tuscany.sca.services.containers</group> + <name>javascript</name> + <version>1.0-incubator-M2-SNAPSHOT</version> + </dependency> + + <component name="javascript.implementationLoader"> + <system:implementation.system class="org.apache.tuscany.container.javascript.JavaScriptImplementationLoader"/> + </component> + + <component name="javascript.componentTypeLoader"> + <system:implementation.system class="org.apache.tuscany.container.javascript.JavaScriptComponentTypeLoader"/> + </component> + + <component name="javascript.componentBuilder"> + <system:implementation.system class="org.apache.tuscany.container.javascript.JavaScriptComponentBuilder"/> + </component> + + <!-- Xml Instance Registry service --> + <component name="xmlInstRegistry"> + <system:implementation.system class="org.apache.tuscany.container.javascript.utils.xmlfromxsd.XmlInstanceRegistryImpl"/> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/resources/META-INF/sca/js.system.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/resources/META-INF/sca/js.system.scdl new file mode 100644 index 0000000000..914c53c10c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/main/resources/META-INF/sca/js.system.scdl @@ -0,0 +1,45 @@ +<?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. +--> +<!-- + JavaScript configuration for the launcher environment. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + + name="org.apache.tuscany.launcher.JavaScriptImplementation"> + + <component name="javascript.implementationLoader"> + <system:implementation.system class="org.apache.tuscany.container.javascript.JavaScriptImplementationLoader"/> + </component> + + <component name="javascript.componentTypeLoader"> + <system:implementation.system class="org.apache.tuscany.container.javascript.JavaScriptComponentTypeLoader"/> + </component> + + <component name="javascript.componentBuilder"> + <system:implementation.system class="org.apache.tuscany.container.javascript.JavaScriptComponentBuilder"/> + </component> + + <!-- Xml Instance Registry service --> + <component name="xmlInstRegistry"> + <system:implementation.system class="org.apache.tuscany.container.javascript.utils.xmlfromxsd.XmlInstanceRegistryImpl"/> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/helloworld/HelloWorldService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/helloworld/HelloWorldService.java new file mode 100644 index 0000000000..e0b1ab2303 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/helloworld/HelloWorldService.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package helloworld; + +import org.apache.axiom.om.OMElement; + +public interface HelloWorldService { + + String sayHello(String s); + OMElement sayE4XHello(OMElement xmlObject); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/helloworld/HelloWorldServiceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/helloworld/HelloWorldServiceImpl.java new file mode 100644 index 0000000000..ac17e29eb0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/helloworld/HelloWorldServiceImpl.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 helloworld; + +import java.io.ByteArrayInputStream; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axiom.om.util.StAXUtils; + +public class HelloWorldServiceImpl implements HelloWorldService { + + public OMElement sayE4XHello(OMElement xmlObject) { + + String helloString = "<hel:getGreetingsResponse xmlns:hel=\"http://helloworld\">" + + "<hel:getGreetingsReturn>Hello from Java Implementation to </hel:getGreetingsReturn>NoString</hel:getGreetingsResponse>"; + + try { + String inputValue = xmlObject.getFirstElement().getText(); + + XMLStreamReader xmlReader = StAXUtils.createXMLStreamReader(new ByteArrayInputStream(helloString.getBytes())); + + StAXOMBuilder staxOMBuilder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(), xmlReader); + OMElement response = staxOMBuilder.getDocumentElement(); + response.getFirstElement().setText(response.getFirstElement().getText() + inputValue); + + return response; + } catch (Exception e) { + return null; + } + } + + public String sayHello(String s) { + return "Hello " + s; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/JavaScriptImplementationLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/JavaScriptImplementationLoaderTestCase.java new file mode 100644 index 0000000000..b7f081bb70 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/JavaScriptImplementationLoaderTestCase.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.MissingResourceException; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; + +/** + * Tests for JavaScriptImplementationLoader + */ +public class JavaScriptImplementationLoaderTestCase extends TestCase { + private CompositeComponent parent; + + private XMLStreamReader reader; + + private DeploymentContext deploymentContext; + + private ClassLoader classLoader; + + private LoaderRegistry registry; + + private JavaScriptImplementationLoader loader; + + public void testNoScriptAttribute() throws LoaderException, XMLStreamException { + expect(reader.getAttributeValue(null, "script")).andReturn(null); + replay(reader); + replay(deploymentContext); + + try { + loader.load(parent, reader, deploymentContext); + fail(); + } catch (MissingResourceException e) { + // ok + } + verify(reader); + verify(deploymentContext); + } + + public void testNoScriptPresent() throws LoaderException, XMLStreamException { + expect(reader.getAttributeValue(null, "script")).andReturn("foo.groovy"); + expect(deploymentContext.getClassLoader()).andReturn(classLoader); + + replay(reader); + replay(deploymentContext); + + JavaScriptImplementationLoader mockLoader = new JavaScriptImplementationLoader(registry) { + protected String loadSource(ClassLoader cl, String resource) throws LoaderException { + assertSame(classLoader, cl); + assertEquals("foo.groovy", resource); + throw new MissingResourceException(resource); + } + }; + try { + mockLoader.load(parent, reader, deploymentContext); + fail(); + } catch (MissingResourceException e) { + assertEquals("foo.groovy", e.getMessage()); + } + verify(reader); + verify(deploymentContext); + } + + public void testLoadScript() throws LoaderException { + String script = + loader.loadSource(getClass().getClassLoader(), "org/apache/tuscany/container/javascript/mock/test.js"); + assertEquals("//Test Script", script); + } + + protected void setUp() throws Exception { + super.setUp(); + registry = createMock(LoaderRegistry.class); + loader = new JavaScriptImplementationLoader(registry); + + parent = createMock(CompositeComponent.class); + reader = createMock(XMLStreamReader.class); + deploymentContext = createMock(DeploymentContext.class); + classLoader = createMock(ClassLoader.class); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/PropertyTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/PropertyTestCase.java new file mode 100644 index 0000000000..7287d7833f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/PropertyTestCase.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.container.javascript; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.apache.tuscany.container.javascript.mock.Greeting; +import org.apache.tuscany.container.javascript.rhino.RhinoScript; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.spi.wire.WireService; +import org.apache.tuscany.test.ArtifactFactory; + +/** + * Tests for component properties + */ +public class PropertyTestCase extends TestCase { + + private static final String SCRIPT = "function greet(name){ return property; }"; + + private RhinoScript implClass; + + /** + * Tests injecting a simple property type on a Javascript implementation instance + */ + public void testPropertyInjection() throws Exception { + /*ModuleScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + Map<String, Object> properties = new HashMap<String, Object>(); + properties.put("property", "bar"); + WireService wireService = ArtifactFactory.createWireService(); + JavaScriptComponent<Greeting> context = new JavaScriptComponent<Greeting>("source", implClass, services, properties, null, scope, wireService, null); + scope.register(context); + Greeting greeting = context.getServiceInstance(); + assertEquals("bar", greeting.greet("foo")); + scope.stop();*/ + } + + protected void setUp() throws Exception { + super.setUp(); + implClass = new RhinoScript("test", SCRIPT); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/RhinoScriptIntrospectorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/RhinoScriptIntrospectorTestCase.java new file mode 100644 index 0000000000..3a51a8f619 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/RhinoScriptIntrospectorTestCase.java @@ -0,0 +1,114 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript; + +import java.io.IOException; +import java.net.URL; +import java.util.Map; +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import helloworld.HelloWorldService; +import junit.framework.TestCase; +import org.apache.tuscany.container.javascript.rhino.RhinoSCAConfig; +import org.apache.tuscany.container.javascript.rhino.RhinoScript; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistryImpl; +import org.apache.tuscany.idl.wsdl.WSDLServiceContract; +import org.apache.tuscany.idl.wsdl.XMLSchemaRegistryImpl; + +public class RhinoScriptIntrospectorTestCase extends TestCase { + + private static final WSDLDefinitionRegistryImpl.Monitor NULL_MONITOR = new WSDLDefinitionRegistryImpl.Monitor() { + public void readingWSDL(String namespace, URL location) { + } + + public void cachingDefinition(String namespace, URL location) { + } + }; + + public void testJavaInterface() throws MissingResourceException, InvalidServiceContractException { + RhinoScript rs = + new RhinoScript("javaInterfaceTest", "SCA = { javaInterface : 'helloworld.HelloWorldService',};", + null, getClass().getClassLoader()); + RhinoSCAConfig scaConfig = new RhinoSCAConfig(rs.getScriptScope()); + JavaScriptIntrospector introspector = + new JavaScriptIntrospector(null, new JavaInterfaceProcessorRegistryImpl()); + ComponentType comonentType = introspector.introspectScript(scaConfig, rs.getClassLoader()); + assertNotNull(comonentType); + Map services = comonentType.getServices(); + assertEquals(1, services.size()); + ServiceDefinition serviceDefinition = (ServiceDefinition) services.values().iterator().next(); + ServiceContract serviceContract = serviceDefinition.getServiceContract(); + assertTrue(serviceContract instanceof JavaServiceContract); + JavaServiceContract javaServiceContract = (JavaServiceContract) serviceContract; + assertEquals(HelloWorldService.class, javaServiceContract.getInterfaceClass()); + } + + public void testWSDLLocation() throws WSDLException { +// RhinoScript rs = new RhinoScript("wsdlLocation", +// "SCA = { wsdlLocation : 'src/test/resources/org/apache/tuscany/container/javascript/rhino/helloworld.wsdl',};", null, getClass() +// .getClassLoader()); +// RhinoSCAConfig scaConfig = new RhinoSCAConfig(rs.getScriptScope()); +// JavaScriptIntrospector introspector = new JavaScriptIntrospector(null); +// ComponentType comonentType = introspector.introspectScript(scaConfig, rs.getClassLoader()); +// assertNotNull(comonentType); +// Map services = comonentType.getServices(); +// assertEquals(1, services.size()); +// ServiceDefinition serviceDefinition = (ServiceDefinition) services.values().iterator().next(); +// ServiceContract serviceContract = serviceDefinition.getServiceContract(); +// assertTrue(serviceContract instanceof WSDLServiceContract); +// WSDLServiceContract wsdlServiceContract = (WSDLServiceContract) serviceContract; +// assertEquals(new QName("http://helloworld", "HelloWorld"), wsdlServiceContract.getPortType().getQName()); + } + + public void testWSDLPortType() throws WSDLException, IOException, MissingResourceException, + InvalidServiceContractException { + RhinoScript rs = new RhinoScript("wsdlPortType", + "SCA = { wsdlPortType : 'HelloWorld', wsdlNamespace : 'http://helloworld',};", null, + getClass().getClassLoader()); + RhinoSCAConfig scaConfig = new RhinoSCAConfig(rs.getScriptScope()); + + WSDLDefinitionRegistryImpl wsdlReg = new WSDLDefinitionRegistryImpl(); + wsdlReg.setSchemaRegistry(new XMLSchemaRegistryImpl()); + wsdlReg.setMonitor(NULL_MONITOR); + URL wsdlURL = + getClass().getClassLoader().getResource("org/apache/tuscany/container/javascript/rhino/helloworld.wsdl"); + wsdlReg.loadDefinition("http://helloworld", wsdlURL); + + JavaScriptIntrospector introspector = + new JavaScriptIntrospector(wsdlReg, new JavaInterfaceProcessorRegistryImpl()); + ComponentType comonentType = introspector.introspectScript(scaConfig, rs.getClassLoader()); + assertNotNull(comonentType); + Map services = comonentType.getServices(); + assertEquals(1, services.size()); + ServiceDefinition serviceDefinition = (ServiceDefinition) services.values().iterator().next(); + ServiceContract serviceContract = serviceDefinition.getServiceContract(); + assertTrue(serviceContract instanceof WSDLServiceContract); + WSDLServiceContract wsdlServiceContract = (WSDLServiceContract) serviceContract; + assertEquals(new QName("http://helloworld", "HelloWorld"), wsdlServiceContract.getPortType().getQName()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/ScriptInvokeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/ScriptInvokeTestCase.java new file mode 100644 index 0000000000..94835591df --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/ScriptInvokeTestCase.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.container.javascript; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.tuscany.container.javascript.mock.Greeting; +import org.apache.tuscany.container.javascript.rhino.RhinoScript; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.test.ArtifactFactory; + +/** + * Tests for invoker JavaScriptComponents + */ +public class ScriptInvokeTestCase extends TestCase { + + private static final String SCRIPT = "function greet(name) { return name }"; + + private RhinoScript rhinoScript; + + /** + * Tests the invocation of a Groovy "script" as opposed to a class + */ + public void testBasicScriptInvocation() throws Exception { +// ModuleScopeContainer scope = new ModuleScopeContainer(null); +// scope.start(); +// List<Class<?>> services = new ArrayList<Class<?>>(); +// services.add(Greeting.class); +// JavaScriptComponent<Greeting> context = new JavaScriptComponent<Greeting>("source", rhinoScript, services, new HashMap<String, Object>(), +// null, scope, ArtifactFactory.createWireService(), null); +// scope.register(context); +// Greeting object = (Greeting) context.getServiceInstance(); +// assertEquals("foo", object.greet("foo")); +// scope.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + rhinoScript = new RhinoScript("test", SCRIPT); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/WireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/WireTestCase.java new file mode 100644 index 0000000000..8bf7f8e74a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/WireTestCase.java @@ -0,0 +1,161 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.javascript; + +import static org.easymock.EasyMock.reportMatcher; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.tuscany.container.javascript.mock.Greeting; +import org.apache.tuscany.container.javascript.rhino.RhinoScript; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.test.ArtifactFactory; +import org.easymock.IArgumentMatcher; + +/** + * Tests for JavaScript component wiring + */ +public class WireTestCase extends TestCase { + + private static final String SCRIPT = + " function setWire(ref){" + + " wire = ref;" + " }" + + " " + + " function greet(name){" + + " return wire.greet(name); " + + " }"; + + private static final String SCRIPT2 = + " function greet(name){" + + " return name; " + + " }"; + + private RhinoScript implClass1; + + private RhinoScript implClass2; + + /** + * Tests a basic invocation down a source wire + */ + public void testReferenceWireInvocation() throws Exception { +// ModuleScopeContainer scope = new ModuleScopeContainer(null); +// scope.start(); +// +// List<Class<?>> services = new ArrayList<Class<?>>(); +// services.add(Greeting.class); +// JavaScriptComponent<Greeting> context = new JavaScriptComponent<Greeting>("source", implClass1, services, properties, null, scope, +// ArtifactFactory.createWireService(), null); +// OutboundWire wire = ArtifactFactory.createOutboundWire("wire", Greeting.class); +// ArtifactFactory.terminateWire(wire); +// +// TargetInvoker invoker = createMock(TargetInvoker.class); +// expect(invoker.isCacheable()).andReturn(false); +// Message response = new MessageImpl(); +// response.setBody("foo"); +// expect(invoker.invoke(eqMessage())).andReturn(response); +// replay(invoker); +// +// for (OutboundInvocationChain chain : wire.getInvocationChains().values()) { +// chain.setTargetInvoker(invoker); +// } +// scope.register(context); +// context.addOutboundWire(wire); +// Greeting greeting = context.getServiceInstance(); +// assertEquals("foo", greeting.greet("foo")); +// verify(invoker); +// +// scope.stop(); + } + + // todo this could be generalized and moved to test module + public static Message eqMessage() { + reportMatcher(new IArgumentMatcher() { + public boolean matches(Object object) { + if (!(object instanceof Message)) { + return false; + } + final Message msg = (Message) object; + Object[] body = (Object[]) msg.getBody(); + return "foo".equals(body[0]); + } + + public void appendTo(StringBuffer stringBuffer) { + } + }); + return null; + } + + /** + * Tests a basic invocation to a target + */ + public void testTargetInvocation() throws Exception { + ModuleScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + JavaScriptComponent context = + new JavaScriptComponent("source", implClass2, new HashMap<String, Object>(), services, null, scope, + ArtifactFactory.createWireService(), null); + scope.register(context); + Operation<Type> operation = new Operation<Type>("greet", null, null, null, false, null); + TargetInvoker invoker = context.createTargetInvoker(null, operation); + assertEquals("foo", invoker.invokeTarget(new String[]{"foo"})); + scope.stop(); + } + + /** + * Tests a basic invocation down a target wire + */ + public void testTargetWireInvocation() throws Exception { + ModuleScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + JavaScriptComponent context = + new JavaScriptComponent("source", implClass2, new HashMap<String, Object>(), services, null, scope, + ArtifactFactory.createWireService(), null); + scope.register(context); + + InboundWire wire = ArtifactFactory.createInboundWire("Greeting", Greeting.class); + ArtifactFactory.terminateWire(wire); + for (InboundInvocationChain chain : wire.getInvocationChains().values()) { + chain.setTargetInvoker(context.createTargetInvoker(null, chain.getOperation())); + } + context.addInboundWire(wire); + Greeting greeting = (Greeting) context.getServiceInstance("Greeting"); + assertEquals("foo", greeting.greet("foo")); + scope.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + implClass1 = new RhinoScript("script1", SCRIPT); + implClass2 = new RhinoScript("script2", SCRIPT2); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/function/HelloWorldTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/function/HelloWorldTestCase.java new file mode 100644 index 0000000000..3db49618e2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/function/HelloWorldTestCase.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript.function; + +import helloworld.HelloWorldService; + +import java.io.ByteArrayInputStream; +import java.net.URL; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axiom.om.util.StAXUtils; +import org.apache.tuscany.test.SCATestCase; +import org.osoa.sca.CompositeContext; +import org.osoa.sca.CurrentCompositeContext; + +/** + * This shows how to test the HelloWorld service component. + */ +public class HelloWorldTestCase extends SCATestCase { + + private CompositeContext context; + + protected void setUp() throws Exception { + URL base = getClass().getResource("/META-INF/sca/js.system.scdl"); + addExtension("JavaScriptContainer", new URL(base, "default.scdl")); + setApplicationSCDL(getClass().getResource("helloworld.scdl")); + super.setUp(); + + context = CurrentCompositeContext.getContext(); + } + + public void testHelloWorld() throws Exception { + HelloWorldService helloWorldService = context.locateService(HelloWorldService.class, "HelloWorldComponent"); + assertEquals(helloWorldService.sayHello("petra"), "Hello petra"); + } + + public void testIntrospectedHelloWorld() throws Exception { + HelloWorldService introspectableService = context.locateService(HelloWorldService.class, "IntrospectableHelloWorldComponent"); + assertEquals(introspectableService.sayHello("petra"), "Hello petra"); + } + + public void testE4XImplInvocation() throws Exception { + HelloWorldService e4xHelloWorldService = context.locateService(HelloWorldService.class, "HelloWorldComponentE4X"); + String xmlInput = "<hel:getGreetings xmlns:hel=\"http://helloworld\"> " + + "<hel:name>TuscanyWorld</hel:name> " + + "</hel:getGreetings>"; + + XMLStreamReader xmlReader = StAXUtils.createXMLStreamReader( + new ByteArrayInputStream(xmlInput.getBytes())); + StAXOMBuilder staxOMBuilder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(), xmlReader); + Object response = e4xHelloWorldService.sayE4XHello(staxOMBuilder.getDocumentElement()); + assertNotNull(response); + assertTrue(response instanceof OMElement); + assertEquals("e4xHello TuscanyWorld", ((OMElement)response).getFirstElement().getText()); + //System.out.println(response); + } + + public void testE4XRefInvocation() throws Exception + { + HelloWorldService e4xHelloWorldService = context.locateService(HelloWorldService.class, "HelloWorldComponentE4X"); + + String initialInput = "JavaClient"; + String jsAddition = " thro e4x reference"; + String endSvcImplResponse = "Hello from Java Implementation to "; + + Object response = e4xHelloWorldService.sayHello(initialInput); + assertNotNull(response); + assertTrue(response instanceof String); + assertEquals(endSvcImplResponse + initialInput + jsAddition, response.toString()); + //System.out.println(response); + } + + public void testHelloWorldProperty() throws Exception { + HelloWorldService helloWorldService = context.locateService(HelloWorldService.class, "HelloWorldProperty"); + assertEquals(helloWorldService.sayHello("petra"), "Kia ora petra"); + System.out.println(helloWorldService.sayHello("petra")); + } + + public void testHelloWorldPropertyDefault() throws Exception { + HelloWorldService helloWorldService = context.locateService(HelloWorldService.class, "HelloWorldPropertyDefault"); + assertEquals(helloWorldService.sayHello("petra"), "Hi petra"); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/function/ScopeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/function/ScopeTestCase.java new file mode 100644 index 0000000000..b823939e6c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/function/ScopeTestCase.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.container.javascript.function; + +import java.net.URL; + +import helloworld.HelloWorldService; + +import org.apache.tuscany.test.SCATestCase; +import org.osoa.sca.CompositeContext; +import org.osoa.sca.CurrentCompositeContext; + +/** + * This shows how to test the HelloWorld service component. + */ +public class ScopeTestCase extends SCATestCase { + + private CompositeContext context; + + protected void setUp() throws Exception { + URL base = getClass().getResource("/META-INF/sca/js.system.scdl"); + addExtension("JavaScriptContainer", new URL(base, "default.scdl")); + setApplicationSCDL(getClass().getResource("scopeTest.scdl")); + super.setUp(); + + context = CurrentCompositeContext.getContext(); + } + +// Composite scope not implemented in core yet +// public void testComposite() throws Exception { +// HelloWorldService composoteScopeService = context.locateService(HelloWorldService.class, "ComposoteScopeService"); +// assertEquals("1", composoteScopeService.sayHello("")); +// assertEquals("2", composoteScopeService.sayHello("")); +// } + + public void testStateless() throws Exception { + HelloWorldService statelessService = context.locateService(HelloWorldService.class, "StatelessComponent"); + assertEquals("1", statelessService.sayHello("")); + // stateless gives a new instance for each request + assertEquals("1", statelessService.sayHello("")); + } + +// Request scope not implemented in core yet +// public void testRequestState() throws Exception { +// HelloWorldService requestService = context.locateService(HelloWorldService.class, "RequestComponent"); +// assertEquals("1", requestService.sayHello("")); +// assertEquals("1", requestService.sayHello("")); +// } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/mock/Greeting.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/mock/Greeting.java new file mode 100644 index 0000000000..e300f73469 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/mock/Greeting.java @@ -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. + */ +package org.apache.tuscany.container.javascript.mock; + +public interface Greeting { + + String setWire(Greeting ref); + + String greet(String name); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/Foo.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/Foo.java new file mode 100644 index 0000000000..397501a23b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/Foo.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.container.javascript.rhino; + +class Foo { + private String s; + + public Foo() { + } + + public String getS() { + return s; + } + + public void setS(String s) { + this.s = s; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoFunctionInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoFunctionInvokerTestCase.java new file mode 100644 index 0000000000..dad61659f3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoFunctionInvokerTestCase.java @@ -0,0 +1,174 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript.rhino; + +import java.io.IOException; + +import junit.framework.TestCase; + +import org.apache.axiom.om.OMElement; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; + +/** + * Tests for the RhinoFunctionInvoker + */ +public class RhinoFunctionInvokerTestCase extends TestCase { + + public RhinoFunctionInvokerTestCase() { + } + + protected void setUp() throws Exception { + super.setUp(); + } + + public void testNoArgsInvoke() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getPetra() {return 'petra';}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getPetra"); + assertNotNull(invoker); + assertEquals("petra", invoker.invoke(null)); + } + + public void testOneArgInvoke() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getS(s) {return s;}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getS"); + assertNotNull(invoker); + assertEquals("petra", invoker.invoke(new Object[] { "petra" })); + } + + public void testMultiArgsInvoke() { + RhinoScript rhinoScript = new RhinoScript("foo", "function concat(x, y) {return x + y}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("concat"); + assertNotNull(invoker); + assertEquals("petrasue", invoker.invoke(new Object[] { "petra", "sue" })); + } + + public void testNoResponseInvoke() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getNull() {}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getNull"); + assertNotNull(invoker); + assertEquals(null, invoker.invoke(new Object[0])); + } + + public void testNullResponseInvoke() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getNull() {return null;}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getNull"); + assertNotNull(invoker); + assertEquals(null, invoker.invoke(new Object[0])); + } + + public void testResponseTypeDefaultString() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getTrue() {return true;}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getTrue"); + assertNotNull(invoker); + Object o = invoker.invoke(new Object[0]); + assertTrue(o instanceof String); + assertEquals("true", o); + } + + public void testResponseTypeBoolean() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getTrue() {return true;}"); + //rhinoScript.setResponseClass("getTrue", Boolean.class); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getTrue", Boolean.class); + assertNotNull(invoker); + assertTrue((Boolean) invoker.invoke(new Object[0])); + } + + public void testResponseTypeStringArray() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getAs() {var as = new Array(1);as[0]='petra';return as;}"); + //rhinoScript.setResponseClass("getAs", new String[0].getClass()); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getAs", new String[0].getClass()); + assertNotNull(invoker); + Object o = invoker.invoke(new Object[0]); + assertNotNull(o); + assertTrue(o.getClass().isArray()); + assertEquals("petra", ((Object[]) o)[0]); + } + + public void testResponseTypeBooleanArray() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getBs() {var bs = new Array(1);bs[0]=true;return bs;}"); + rhinoScript.setResponseClass("getBs", new Boolean[0].getClass()); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getBs", new Boolean[0].getClass()); + assertNotNull(invoker); + Object o = invoker.invoke(new Object[0]); + assertNotNull(o); + assertTrue(o.getClass().isArray()); + assertTrue(((Boolean[]) o)[0]); + } + + public void testRequestCustomType() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getFooS(foo) {return foo.getS();}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getFooS"); + assertNotNull(invoker); + + Foo foo = new Foo(); + foo.setS("petra"); + Object o = invoker.invoke(new Object[] { foo }); + assertEquals(foo.getS(), o); + } + + public void testResponseCustomType() { + RhinoScript rhinoScript = new RhinoScript("foo", + "importClass(Packages.org.apache.tuscany.container.javascript.rhino.Foo);function getFoo(s) {var foo = new Foo(); foo.setS(s);return foo;}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getFoo"); + assertNotNull(invoker); + + Object o = invoker.invoke(new Object[] { "petra" }); + assertNotNull(o); + assertEquals("petra", ((Foo) o).getS()); + } + + public void testXMLRequest() throws XmlException, IOException { + RhinoScript rhinoScript = new RhinoScript("foo", "function isXML(x) {return 'xml' == (typeof x);}"); + //rhinoScript.setResponseClass("isXML", Boolean.class); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("isXML", Boolean.class); + assertNotNull(invoker); + + Object xml = XmlObject.Factory.parse("<a><b/></a>"); + assertTrue((Boolean) invoker.invoke(new Object[] { xml })); + + Object notXML = "notXML"; + assertFalse((Boolean) invoker.invoke(new Object[] { notXML })); + } + + public void testXMLResponse() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getXML(s) {return <a> { s } </a>;}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getXML"); + assertNotNull(invoker); + + Object xml = invoker.invoke(new Object[] { "petra" }); + assertNotNull(xml); + assertTrue(xml instanceof OMElement); + assertEquals("<a>petra</a>", ((OMElement) xml).toString()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoSCAConfigTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoSCAConfigTestCase.java new file mode 100644 index 0000000000..cddaa9c46f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoSCAConfigTestCase.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript.rhino; + +import junit.framework.TestCase; + +import org.apache.tuscany.spi.model.Scope; + +public class RhinoSCAConfigTestCase extends TestCase { + + public void testJavaInteface() { + RhinoScript rs = new RhinoScript("javaInterface", "SCA = { javaInterface : 'Test' }"); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(scaConfig.hasSCAConfig()); + assertEquals("Test", scaConfig.getJavaInterface()); + } + + public void testWSDLLocation() { + RhinoScript rs = new RhinoScript("wsdlLocation", "SCA = { wsdlLocation : 'Test' }"); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(scaConfig.hasSCAConfig()); + assertEquals("Test", scaConfig.getWSDLLocation()); + } + + public void testWSDLNamespace() { + RhinoScript rs = new RhinoScript("wsdlNamespace", "SCA = { wsdlNamespace : 'Test' }"); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(scaConfig.hasSCAConfig()); + assertEquals("Test", scaConfig.getWSDLNamespace()); + } + + public void testWSDLPortType() { + RhinoScript rs = new RhinoScript("wsdlPortType", "SCA = { wsdlPortType : 'Test' }"); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(scaConfig.hasSCAConfig()); + assertEquals("Test", scaConfig.getWSDLPortType()); + } + + public void testScopeStateless() { + RhinoScript rs = new RhinoScript("testScopeStateless", "SCA = { scope : 'stateless', javaInterface : 'helloworld.HelloWorldService'}"); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(scaConfig.hasSCAConfig()); + assertEquals(Scope.STATELESS, scaConfig.getScope()); + } + + public void testScopeComposite() { + RhinoScript rs = new RhinoScript("testScopeComposite", "SCA = { scope : 'composite', javaInterface : 'helloworld.HelloWorldService'}"); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(scaConfig.hasSCAConfig()); + assertEquals(Scope.MODULE, scaConfig.getScope()); // TODO + } + + public void testScopeConversational() { + RhinoScript rs = new RhinoScript("testScopeConversational", "SCA = { scope : 'conversational', javaInterface : 'helloworld.HelloWorldService'}"); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(scaConfig.hasSCAConfig()); + assertEquals(Scope.SESSION, scaConfig.getScope()); + } + + public void testScopeRequest() { + RhinoScript rs = new RhinoScript("testScopeRequest", "SCA = { scope : 'request', javaInterface : 'helloworld.HelloWorldService'}"); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(scaConfig.hasSCAConfig()); + assertEquals(Scope.REQUEST, scaConfig.getScope()); + } + + public void testBadScope() { + RhinoScript rs = new RhinoScript("testScopeStateless", "SCA = { scope : 'rubbish', javaInterface : 'helloworld.HelloWorldService'}"); + try { + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + fail("expecting bad scope exception: " + scaConfig); + } catch (IllegalArgumentException e) { + } + } + + public void testNoConfig() { + RhinoScript rs = new RhinoScript("javaInterface", ""); + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + assertTrue(!scaConfig.hasSCAConfig()); + } + + public void testNoService() { + RhinoScript rs = new RhinoScript("javaInterface", "SCA = {}"); + try { + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + fail("expecting no service exception: " + scaConfig); + } catch (IllegalArgumentException e) { + } + } + + public void testDupicateInteface() { + RhinoScript rs = new RhinoScript("javaInterface", "SCA = { javaInterface : 'Test', wsdlLocation : 'Test' }"); + try { + RhinoSCAConfig scaConfig = rs.getSCAConfig(); + fail("expecting multiple service exception: " + scaConfig); + } catch (IllegalArgumentException e) { + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptInstanceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptInstanceTestCase.java new file mode 100644 index 0000000000..76d6c7c49d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptInstanceTestCase.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.container.javascript.rhino; + +import junit.framework.TestCase; + +/** + * Tests for the RhinoScriptInstance + */ +public class RhinoScriptInstanceTestCase extends TestCase { + + public RhinoScriptInstanceTestCase() { + + } + + protected void setUp() throws Exception { + super.setUp(); + } + + public void testInvokeFunction() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getPetra() {return 'petra';}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + assertEquals("petra", instance.invokeFunction("getPetra", new Object[0])); + } + + public void testCreateRhinoFunctionInvoker() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getPetra() {return 'petra';}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + RhinoFunctionInvoker invoker = instance.createRhinoFunctionInvoker("getPetra"); + assertNotNull(invoker); + assertEquals("petra", invoker.invoke(new Object[0])); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptTestCase.java new file mode 100644 index 0000000000..ab684c39ce --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/rhino/RhinoScriptTestCase.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.javascript.rhino; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +/** + * Tests for the RhinoScript + */ +public class RhinoScriptTestCase extends TestCase { + + public RhinoScriptTestCase() { + + } + + protected void setUp() throws Exception { + super.setUp(); + } + + public void testSimpleConstructor() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getPetra() {return 'petra';}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + assertEquals("petra", instance.invokeFunction("getPetra", new Object[0])); + } + + public void testFullConstructor() { + ClassLoader cl = getClass().getClassLoader(); + Map<String, Object> contexts = new HashMap<String, Object>(); + contexts.put("name", "petra"); + RhinoScript rhinoScript = new RhinoScript("foo", "function getName() {return name;}", contexts, cl); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + assertEquals("petra", instance.invokeFunction("getName", new Object[0])); + } + + public void testCreateInstance() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getPetra() {return 'petra';}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + assertNotNull(instance); + } + + public void testCreateInstanceWithContext() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getName() {return name;}"); + Map<String, Object> contexts = new HashMap<String, Object>(); + contexts.put("name", "petra"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(contexts); + assertEquals("petra", instance.invokeFunction("getName", new Object[0])); + } + + public void testDefaultResponseType() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getX() {return 42;}"); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + assertEquals("42", instance.invokeFunction("getX", new Object[0])); + } + + public void testSetResponseType() { + RhinoScript rhinoScript = new RhinoScript("foo", "function getX() {return 42;}"); + rhinoScript.setResponseClass("getX", Integer.class); + RhinoScriptInstance instance = rhinoScript.createRhinoScriptInstance(); + Object x = instance.invokeFunction("getX", new Object[0], Integer.class); + assertTrue(x instanceof Integer); + assertEquals(new Integer(42), x); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDGeneratorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDGeneratorTestCase.java new file mode 100644 index 0000000000..15752bdaa1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/java/org/apache/tuscany/container/javascript/utils/xmlfromxsd/XMLfromXSDGeneratorTestCase.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.container.javascript.utils.xmlfromxsd; + +import junit.framework.TestCase; + +public class XMLfromXSDGeneratorTestCase extends TestCase { + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + /*public void testXMLInstance_SDO_based_1() + { + String[] arguments = new String[] { "-xsd", "sequences.xsd", + "-st", "MixedQuote", + "-stn", "http://www.example.com/sequences", + "-o", "target/xmlFromxsd-source", + "-of", "sequences_sdo.xml" + }; + + XMLfromXSDGenerator.main(arguments); + //File file = new File("target/java2wsdl-source/CustomerValue.wsdl"); + //assertTrue(file.exists() && file.isFile()); + } + + public void testXMLInstance_SDO_based_2() + { + try + { + XMLfromXSDConfiguration config = new XMLfromXSDConfiguration(); + config.setXsdFileName("interopdoc.wsdl"); + config.setSchemaTypeName("ComplexDocument"); + config.setSchemaTypeNamespaceURI("http://soapinterop.org/"); + config.setXmlOutputLocation("target/xmlFromxsd-source"); + config.setXmlFileName("interopdoc_sdo.xml"); + + XMLGeneratorFactory.getInstance().createGenerator(XMLGenerator.SDO_BASED).generateXML(config); + //XMLGeneratorFactory.getInstance().createGenerator(XMLGenerator.XMLBEANS_BASED).generateXML(config); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + public void testXMLInstance_SDO_based_3() + { + try + { + XMLfromXSDConfiguration config = new XMLfromXSDConfiguration(); + config.setXsdFileName("helloworld.wsdl"); + //config.setSchemaTypeName("getGreetings"); + config.setSchemaTypeName("ComplexGreetings"); + config.setSchemaTypeNamespaceURI("http://helloworldaxis.samples.tuscany.apache.org"); + config.setXmlOutputLocation("target/xmlFromxsd-source"); + config.setXmlFileName("helloworld_sdo.xml"); + + XMLGeneratorFactory.getInstance().createGenerator(XMLGenerator.SDO_BASED).generateXML(config); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + }*/ + + public void testXMLInstance_XB_based_1() { + String[] arguments = new String[] { "-xsd", "src/test/resources/sequences.xsd", "-st", "mixedStockQuote", "-stn", + "http://www.example.com/sequences", "-o", "target/xmlFromxsd-source", "-of", "sequences_xb.xml" }; + + XMLfromXSDGenerator.generatorType = XMLGenerator.XMLBEANS_BASED; + XMLfromXSDGenerator.main(arguments); + /* + * File file = new File("target/java2wsdl-source/CustomerValue.wsdl"); assertTrue(file.exists() && file.isFile()); + */ + } + + public void testXMLInstance_XB_based_2() { + try { + XMLfromXSDConfiguration config = new XMLfromXSDConfiguration(); + config.setXsdFileName("interopdoc.wsdl"); + config.setSchemaTypeName("ComplexDocument"); + config.setSchemaTypeNamespaceURI("http://soapinterop.org/"); + config.setXmlOutputLocation("target/xmlFromxsd-source"); + config.setXmlFileName("interopdoc_xb.xml"); + + XMLGeneratorFactory.getInstance().createGenerator(XMLGenerator.XMLBEANS_BASED).generateXML(config); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void testXMLInstance_XB_based_3() { + try { + XMLfromXSDConfiguration config = new XMLfromXSDConfiguration(); + config.setXsdFileName("org/apache/tuscany/container/javascript/rhino/helloworld.wsdl"); + // config.setXsdFileName("helloworld.wsdl"); + config.setSchemaTypeName("getGreetings"); + // config.setSchemaTypeName("ComplexGreetings"); + config.setSchemaTypeNamespaceURI("http://helloworld"); + config.setXmlOutputLocation("target/xmlFromxsd-source"); + config.setXmlFileName("helloworld_xb.xml"); + + XMLGeneratorFactory.getInstance().createGenerator(XMLGenerator.XMLBEANS_BASED).generateXML(config); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/AccountService.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/AccountService.wsdl new file mode 100644 index 0000000000..2a56a3c496 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/AccountService.wsdl @@ -0,0 +1,242 @@ +<?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. + --> +<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:tns="http://www.bigbank.com/Account/" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:account="http://www.bigbank.com/Account/" + targetNamespace="http://www.bigbank.com/Account/" + name="AccountService"> + + <wsdl:types> + <xsd:schema targetNamespace="http://www.bigbank.com/Account/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:account="http://www.bigbank.com/Account/" + xmlns:sdojava="commonj.sdo/java" + sdojava:package="org.apache.tuscany.samples.bigbank.account"> + + <xsd:element name="getAccountReportWrapped0"> + <xsd:complexType> + <xsd:sequence> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element name="getAccountReportWrapped0Response"> + <xsd:complexType> + <xsd:sequence> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + + <xsd:element name="getAccountReportWrapped1"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="customerID" type="xsd:string"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element name="getAccountReportWrapped1Response"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="accountReport" type="account:AccountReport"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + + <xsd:element name="getAccountReportWrappedN"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="customerID" type="xsd:string"/> + <xsd:element name="customerID2" type="xsd:int"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element name="getAccountReportWrappedNResponse"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="accountReport" type="account:AccountReport"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + + <xsd:element name="getAccountReportBare0" type="xsd:string"/> + <xsd:element name="getAccountReportBare0Response" type="xsd:int"/> + + <xsd:element name="getAccountReportBare1Simple" type="xsd:string"/> + <xsd:element name="getAccountReportBare1SimpleResponse" type="xsd:int"/> + + <xsd:element name="getAccountReportBare1Complex" type="account:AccountRequest"/> + <xsd:element name="getAccountReportBare1ComplexResponse" type="account:AccountReport"/> + + <xsd:complexType name="AccountRequest"> + <xsd:sequence> + <xsd:element name="customerID" type="xsd:string"/> + </xsd:sequence> + </xsd:complexType> + + <xsd:complexType name="AccountReport"> + <xsd:sequence> + <xsd:element name="accountSummaries" type="account:AccountSummary" maxOccurs="unbounded"/> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="AccountSummary"> + <xsd:attribute name="accountNumber" type="xsd:string"/> + <xsd:attribute name="accountType" type="xsd:string"/> + <xsd:attribute name="balance" type="xsd:float"/> + </xsd:complexType> + + </xsd:schema> + </wsdl:types> + + <wsdl:message name="getAccountReportWrapped0Request"> + <wsdl:part element="account:getAccountReportWrapped0" name="getAccountReportWrapped0Request"/> + </wsdl:message> + <wsdl:message name="getAccountReportWrapped0Response"> + <wsdl:part element="account:getAccountReportWrapped0Response" name="getAccountReportWrapped0Response"/> + </wsdl:message> + + <wsdl:message name="getAccountReportWrapped1Request"> + <wsdl:part element="account:getAccountReportWrapped1" name="getAccountReportWrapped1Request"/> + </wsdl:message> + <wsdl:message name="getAccountReportWrapped1Response"> + <wsdl:part element="account:getAccountReportWrapped1Response" name="getAccountReportWrapped1Response"/> + </wsdl:message> + + <wsdl:message name="getAccountReportWrappedNRequest"> + <wsdl:part element="account:getAccountReportWrappedN" name="getAccountReportWrappedNRequest"/> + </wsdl:message> + <wsdl:message name="getAccountReportWrappedNResponse"> + <wsdl:part element="account:getAccountReportWrappedNResponse" name="getAccountReportWrappedNResponse"/> + </wsdl:message> + + <wsdl:message name="getAccountReportBare0Request"> + </wsdl:message> + <wsdl:message name="getAccountReportBare0Response"> + </wsdl:message> + + <wsdl:message name="getAccountReportBare1SimpleRequest"> + <wsdl:part element="account:getAccountReportBare1Simple" name="getAccountReportBare1SimpleRequest"/> + </wsdl:message> + <wsdl:message name="getAccountReportBare1SimpleResponse"> + <wsdl:part element="account:getAccountReportBare1SimpleResponse" name="getAccountReportBare1SimpleResponse"/> + </wsdl:message> + + <wsdl:message name="getAccountReportBare1ComplexRequest"> + <wsdl:part element="account:getAccountReportBare1Complex" name="getAccountReportBare1ComplexRequest"/> + </wsdl:message> + <wsdl:message name="getAccountReportBare1ComplexResponse"> + <wsdl:part element="account:getAccountReportBare1ComplexResponse" name="getAccountReportBare1ComplexResponse"/> + </wsdl:message> + + <wsdl:portType name="Account_Service"> + <wsdl:operation name="getAccountReportWrapped0"> + <wsdl:input message="tns:getAccountReportWrapped0Request"/> + <wsdl:output message="tns:getAccountReportWrapped0Response"/> + </wsdl:operation> + <wsdl:operation name="getAccountReportWrapped1"> + <wsdl:input message="tns:getAccountReportWrapped1Request"/> + <wsdl:output message="tns:getAccountReportWrapped1Response"/> + </wsdl:operation> + <wsdl:operation name="getAccountReportWrappedN"> + <wsdl:input message="tns:getAccountReportWrappedNRequest"/> + <wsdl:output message="tns:getAccountReportWrappedNResponse"/> + </wsdl:operation> + <wsdl:operation name="getAccountReportBare0"> + <wsdl:input message="tns:getAccountReportBare0Request"/> + <wsdl:output message="tns:getAccountReportBare0Response"/> + </wsdl:operation> + <wsdl:operation name="getAccountReportBare1Simple"> + <wsdl:input message="tns:getAccountReportBare1SimpleRequest"/> + <wsdl:output message="tns:getAccountReportBare1SimpleResponse"/> + </wsdl:operation> + <wsdl:operation name="getAccountReportBare1Complex"> + <wsdl:input message="tns:getAccountReportBare1ComplexRequest"/> + <wsdl:output message="tns:getAccountReportBare1ComplexResponse"/> + </wsdl:operation> + </wsdl:portType> + <wsdl:binding name="AccountServiceSOAP" type="tns:Account_Service"> + <soap:binding style="document" + transport="http://schemas.xmlsoap.org/soap/http"/> + <wsdl:operation name="getAccountReportWrapped0"> + <soap:operation + soapAction="http://www.bigbank.com/Account/getAccountReportWrapped0"/> + <wsdl:input> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + <wsdl:operation name="getAccountReportWrapped1"> + <soap:operation + soapAction="http://www.bigbank.com/Account/getAccountReportWrapped1"/> + <wsdl:input> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + <wsdl:operation name="getAccountReportWrappedN"> + <soap:operation + soapAction="http://www.bigbank.com/Account/getAccountReportWrappedN"/> + <wsdl:input> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + <wsdl:operation name="getAccountReportBare0"> + <soap:operation + soapAction="http://www.bigbank.com/Account/getAccountReportBare0"/> + <wsdl:input> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + <wsdl:operation name="getAccountReportBare1Simple"> + <soap:operation + soapAction="http://www.bigbank.com/Account/getAccountReportBare1Simple"/> + <wsdl:input> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + <wsdl:operation name="getAccountReportBare1Complex"> + <soap:operation + soapAction="http://www.bigbank.com/Account/getAccountReportBare1Complex"/> + <wsdl:input> + <soap:body use="literal"/> + </wsdl:input> + <wsdl:output> + <soap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + </wsdl:binding> + <wsdl:service name="AccountService"> + <wsdl:port binding="tns:AccountServiceSOAP" + name="AccountServiceSOAP"> + <soap:address location="http://localhost:8080/sample-account/services/AccountService"/> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/interopdoc.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/interopdoc.wsdl new file mode 100644 index 0000000000..820c26ca34 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/interopdoc.wsdl @@ -0,0 +1,180 @@ +<?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="InteropTestDoc" targetNamespace="http://soapinterop.org/" + xmlns="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://soapinterop.org/" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> + + <types> + + <xsd:schema elementFormDefault="qualified" targetNamespace="http://soapinterop.org/" xmlns:interop="http://soapinterop.org/"> + + <xsd:element name="SingleTag"> + <xsd:complexType> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="1" name="SingleTag" type="interop:SingleTag"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + + <xsd:complexType name="SingleTag"/> + <xsd:element name="SingleTagResponse"> + <xsd:complexType> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="1" name="SingleTag" type="interop:SingleTag"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element name="SimpleDocument"> + <xsd:complexType> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="1" name="SimpleDocument" type="interop:SimpleDocument"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:complexType name="SimpleDocument"> + <xsd:simpleContent> + <xsd:extension base="xsd:string"/> + </xsd:simpleContent> + </xsd:complexType> + <xsd:element name="SimpleDocumentResponse"> + <xsd:complexType> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="1" name="SimpleDocument" type="interop:SimpleDocument"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element name="ComplexDocument"> + <xsd:complexType> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="1" name="ComplexDocument" type="interop:ComplexDocument"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:complexType name="ComplexDocument"> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="1" name="simpleDoc" type="interop:ArrayOfSimpleDocument"/> + <xsd:element minOccurs="0" maxOccurs="1" name="child" type="interop:ChildDocument"/> + </xsd:sequence> + <xsd:attribute name="AnAttribute" type="xsd:string"/> + </xsd:complexType> + <xsd:complexType name="ArrayOfSimpleDocument"> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="unbounded" name="SimpleDocument" nillable="true" type="interop:SimpleDocument"/> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="ChildDocument"> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="1" name="childSimpleDoc" type="interop:ArrayOfSimpleDocument"/> + </xsd:sequence> + </xsd:complexType> + <xsd:element name="ComplexDocumentResponse"> + <xsd:complexType> + <xsd:sequence> + <xsd:element minOccurs="0" maxOccurs="1" name="ComplexDocument" type="interop:ComplexDocument"/> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + + </xsd:schema> + + </types> + + <message name="SingleTagSoapIn"> + <part name="parameters" element="tns:SingleTag"/> + </message> + <message name="SingleTagSoapOut"> + <part name="outputDoc" element="tns:SingleTagResponse"/> + </message> + <message name="SimpleDocumentSoapIn"> + <part name="parameters" element="tns:SimpleDocument"/> + </message> + <message name="SimpleDocumentSoapOut"> + <part name="outputDoc" element="tns:SimpleDocumentResponse"/> + </message> + <message name="ComplexDocumentSoapIn"> + <part name="parameters" element="tns:ComplexDocument"/> + </message> + <message name="ComplexDocumentSoapOut"> + <part name="outputDoc" element="tns:ComplexDocumentResponse"/> + </message> + + <portType name="DocTestPortType"> + + <operation name="SingleTag"> + <input message="tns:SingleTagSoapIn"/> + <output message="tns:SingleTagSoapOut"/> + </operation> + <operation name="SimpleDocument"> + <input message="tns:SimpleDocumentSoapIn"/> + <output message="tns:SimpleDocumentSoapOut"/> + </operation> + <operation name="ComplexDocument"> + <input message="tns:ComplexDocumentSoapIn"/> + <output message="tns:ComplexDocumentSoapOut"/> + </operation> + + </portType> + + <binding name="doc_test_binding" type="tns:DocTestPortType"> + <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + + <operation name="SingleTag"> + <soap:operation soapAction="http://soapinterop.org/SingleTag"/> + <input> + <soap:body use="literal"/> + </input> + <output> + <soap:body use="literal"/> + </output> + </operation> + + <operation name="SimpleDocument"> + <soap:operation soapAction="http://soapinterop.org/SimpleDocument"/> + <input> + <soap:body use="literal"/> + </input> + <output> + <soap:body use="literal"/> + </output> + </operation> + + <operation name="ComplexDocument"> + <soap:operation soapAction="http://soapinterop.org/ComplexDocument"/> + <input> + <soap:body use="literal"/> + </input> + <output> + <soap:body use="literal"/> + </output> + </operation> + </binding> + + <service name="interopDocSvc"> + + <port name="interopDocPort" binding="tns:doc_test_binding"> + <soap:address location="http://www.whitemesa.net/interopdoc"/> + </port> + + </service> + +</definitions> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/HelloWorld.componentType b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/HelloWorld.componentType new file mode 100644 index 0000000000..bd1e9445c1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/HelloWorld.componentType @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="ASCII"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> + +<componentType xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + + <service name="HelloWorldService"> + <interface.java interface="helloworld.HelloWorldService"/> + </service> +</componentType> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/HelloWorld.js b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/HelloWorld.js new file mode 100644 index 0000000000..520153329e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/HelloWorld.js @@ -0,0 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +function sayHello(s) { + return "Hello " + s; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/IntrospectableHelloWorld.js b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/IntrospectableHelloWorld.js new file mode 100644 index 0000000000..2f6b7e0675 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/IntrospectableHelloWorld.js @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +SCA = { + 'javaInterface' : 'helloworld.HelloWorldService' +} + +function sayHello(s) { + return "Hello " + s; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/compositeScope.js b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/compositeScope.js new file mode 100644 index 0000000000..4684b89e66 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/compositeScope.js @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +SCA = { + scope : 'composite', + javaInterface : 'helloworld.HelloWorldService' +} + +x = 0; + +function sayHello(s) { + x = x + 1; + return x; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/e4x.componentType b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/e4x.componentType new file mode 100644 index 0000000000..8f2d906f58 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/e4x.componentType @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="ASCII"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> + +<componentType xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + + <service name="HelloWorldService"> +<!-- <interface.wsdl interface="http://integration.rhino.container.tuscany.apache.org#HelloWorld"/> --> + <interface.java interface="helloworld.HelloWorldService"/> + </service> + + <reference name="extHelloWorldService"> + <interface.java interface="helloworld.HelloWorldService"/> + </reference> + + +</componentType> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/e4x.js b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/e4x.js new file mode 100644 index 0000000000..3e9c00fcb9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/e4x.js @@ -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. + */ + +function sayE4XHello(xmlIn) { + + var greeting = "e4xHello " + xmlIn..*::name; + var xmlOut = getXmlObject("http://helloworld","getGreetingsResponse"); + + var ns = new Namespace("http://helloworld"); + xmlOut.ns::getGreetingsReturn = greeting; + + return xmlOut; +} + + + + function sayHello(name) { + //create XML Request Object + var xmlIn = getXmlObject("http://helloworld","getGreetings"); + var ns = new Namespace("http://helloworld"); + xmlIn.ns::name = name + " thro e4x reference"; + + //invoke service thro service reference and obtain XML Response + var xmlOut = extHelloWorldService.sayE4XHello(xmlIn); + + //extract the content of response XML and return as string + var greeting = "" + xmlOut..*::getGreetingsReturn; + return greeting; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/helloworld.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/helloworld.scdl new file mode 100644 index 0000000000..c3c4f5c669 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/helloworld.scdl @@ -0,0 +1,50 @@ +<?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. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:js="http://incubator.apache.org/tuscany/xmlns/container/js/1.0-incubator-M2" + + name="HelloWorldComposite"> + + <component name="HelloWorldComponent"> + <js:implementation.js script="org/apache/tuscany/container/javascript/function/HelloWorld.js"/> + </component> + + <component name="IntrospectableHelloWorldComponent"> + <js:implementation.js script="org/apache/tuscany/container/javascript/function/IntrospectableHelloWorld.js"/> + </component> + + <component name="HelloWorldComponentE4X"> + <js:implementation.js script="org/apache/tuscany/container/javascript/function/e4x.js"/> + <reference name="extHelloWorldService" target="HelloWorldJavaReference">HelloWorldJavaReference</reference> + </component> + + <component name="HelloWorldJavaReference"> + <implementation.java class="helloworld.HelloWorldServiceImpl"/> + </component> + + <component name="HelloWorldProperty"> + <js:implementation.js script="org/apache/tuscany/container/javascript/function/propertyTest.js"/> + <property name="GREETING">Kia ora</property> + </component> + + <component name="HelloWorldPropertyDefault"> + <js:implementation.js script="org/apache/tuscany/container/javascript/function/propertyTest.js"/> + </component> +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/propertyTest.componentType b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/propertyTest.componentType new file mode 100644 index 0000000000..8e46971ea3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/propertyTest.componentType @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="ASCII"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+<componentType xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+
+ <service name="HelloWorldService">
+ <interface.java interface="helloworld.HelloWorldService"/>
+ </service>
+
+ <property name="GREETING" type="xsd:string">Hi</property>
+
+</componentType>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/propertyTest.js b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/propertyTest.js new file mode 100644 index 0000000000..96e21d0c75 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/propertyTest.js @@ -0,0 +1,21 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+function sayHello(s) {
+ return GREETING + ' ' + s;
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/requestScope.js b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/requestScope.js new file mode 100644 index 0000000000..bf8f840b91 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/requestScope.js @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +SCA = { + scope : 'request', + javaInterface : 'helloworld.HelloWorldService' +} + +x = 0; + +function sayHello(s) { + x = x + 1; + return x; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/scopeTest.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/scopeTest.scdl new file mode 100644 index 0000000000..3754d69da1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/scopeTest.scdl @@ -0,0 +1,37 @@ +<?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. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:js="http://incubator.apache.org/tuscany/xmlns/container/js/1.0-incubator-M2" + + name="HelloWorldComposite"> + + <component name="StatelessComponent"> + <js:implementation.js script="org/apache/tuscany/container/javascript/function/statelessScope.js"/> + </component> + + <!-- component name="RequestComponent"> + <js:implementation.js script="org/apache/tuscany/container/javascript/function/requestScope.js"/> + </component --> + + <!-- component name="CompositeScopeComponent"> + <js:implementation.js script="org/apache/tuscany/container/javascript/function/compositeScope.js"/> + </component --> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/statelessScope.js b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/statelessScope.js new file mode 100644 index 0000000000..21f5104859 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/function/statelessScope.js @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +SCA = { + scope : 'stateless', + javaInterface : 'helloworld.HelloWorldService' +} + +x = 0; + +function sayHello(s) { + x = x + 1; + return x; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/mock/test.js b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/mock/test.js new file mode 100644 index 0000000000..ef2694b475 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/mock/test.js @@ -0,0 +1 @@ +//Test Script
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/rhino/helloworld.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/rhino/helloworld.wsdl new file mode 100644 index 0000000000..67067f044a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/org/apache/tuscany/container/javascript/rhino/helloworld.wsdl @@ -0,0 +1,78 @@ +<?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. + --> +<wsdl:definitions targetNamespace="http://helloworld" xmlns:tns="http://helloworld" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" + name="helloworld"> + + <wsdl:types> + <schema elementFormDefault="qualified" targetNamespace="http://helloworld" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/2001/XMLSchema"> + + <element name="getGreetings"> + <complexType> + <sequence> + <element name="name" type="xsd:string"/> + </sequence> + </complexType> + </element> + + <element name="getGreetingsResponse"> + <complexType> + <sequence> + <element name="getGreetingsReturn" type="xsd:string"/> + </sequence> + </complexType> + </element> + </schema> + </wsdl:types> + + <wsdl:message name="getGreetingsRequest"> + <wsdl:part element="tns:getGreetings" name="parameters"/> + </wsdl:message> + + <wsdl:message name="getGreetingsResponse"> + <wsdl:part element="tns:getGreetingsResponse" name="parameters"/> + </wsdl:message> + + <wsdl:portType name="HelloWorld"> + <wsdl:operation name="getGreetings"> + <wsdl:input message="tns:getGreetingsRequest" name="getGreetingsRequest"/> + <wsdl:output message="tns:getGreetingsResponse" name="getGreetingsResponse"/> + </wsdl:operation> + </wsdl:portType> + + <wsdl:binding name="HelloWorldSoapBinding" type="tns:HelloWorld"> + <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + <wsdl:operation name="getGreetings"> + <wsdlsoap:operation soapAction=""/> + <wsdl:input name="getGreetingsRequest"> + <wsdlsoap:body use="literal"/> + </wsdl:input> + <wsdl:output name="getGreetingsResponse"> + <wsdlsoap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + </wsdl:binding> + + <wsdl:service name="HelloWorldService"> + <wsdl:port binding="tns:HelloWorldSoapBinding" name="HelloWorldSoapPort"> + <wsdlsoap:address location="http://localhost:8080/sample-helloworldws/services/HelloWorldWebService"/> + </wsdl:port> + </wsdl:service> + +</wsdl:definitions> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/sequences.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/sequences.xsd new file mode 100644 index 0000000000..a565f3fa65 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.javascript/src/test/resources/sequences.xsd @@ -0,0 +1,100 @@ +<?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. + --> +<xsd:schema xmlns:seq="http://www.example.com/sequences" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + targetNamespace="http://www.example.com/sequences"> + + <xsd:element name="mixedStockQuote" type="seq:MixedQuote" /> + <xsd:element name="rc" type="seq:RepeatingChoice" /> + <xsd:element name="mrc" type="seq:MixedRepeatingChoice" /> + <xsd:element name="rc2" type="seq:TwoRCs" /> + <xsd:element name="mrc2" type="seq:TwoRCsMixed" /> + + + + <xsd:complexType mixed="true" name="MixedQuote"> + <xsd:sequence> + <xsd:element name="symbol" type="xsd:string" /> + <xsd:element name="companyName" type="xsd:string" /> + <xsd:element name="price" type="xsd:decimal" /> + <xsd:element name="open1" type="xsd:decimal" /> + <xsd:element name="high" type="xsd:decimal" /> + <xsd:element name="low" type="xsd:decimal" /> + <xsd:element name="volume" type="xsd:double" /> + <xsd:element name="change1" type="xsd:double" /> + <xsd:element maxOccurs="unbounded" minOccurs="0" + name="quotes" type="seq:MixedQuote" /> + </xsd:sequence> + </xsd:complexType> + + + <xsd:complexType name="RepeatingChoice"> + <xsd:choice maxOccurs="unbounded" minOccurs="0"> + <xsd:element name="a" type="xsd:string" /> + <xsd:element name="b" type="xsd:int" /> + </xsd:choice> + </xsd:complexType> + + + <xsd:complexType mixed="true" name="MixedRepeatingChoice"> + <xsd:choice maxOccurs="unbounded" minOccurs="0"> + <xsd:element name="a" type="xsd:string" /> + <xsd:element name="b" type="xsd:int" /> + </xsd:choice> + </xsd:complexType> + + + <xsd:complexType name="TwoRCs"> + <xsd:sequence> + + <xsd:choice maxOccurs="unbounded" minOccurs="0"> + <xsd:element name="a" type="xsd:string" /> + <xsd:element name="b" type="xsd:int" /> + </xsd:choice> + + <xsd:element name="split" type="xsd:string" /> + + <xsd:choice maxOccurs="unbounded" minOccurs="0"> + <xsd:element name="y" type="xsd:string" /> + <xsd:element name="z" type="xsd:int" /> + </xsd:choice> + + </xsd:sequence> + </xsd:complexType> + + <xsd:complexType mixed="true" name="TwoRCsMixed"> + <xsd:sequence> + + <xsd:choice maxOccurs="unbounded" minOccurs="0"> + <xsd:element name="a" type="xsd:string" /> + <xsd:element name="b" type="xsd:int" /> + </xsd:choice> + + <xsd:element name="split" type="xsd:string" /> + + <xsd:choice maxOccurs="unbounded" minOccurs="0"> + <xsd:element name="y" type="xsd:string" /> + <xsd:element name="z" type="xsd:int" /> + </xsd:choice> + + </xsd:sequence> + </xsd:complexType> + +</xsd:schema> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/pom.xml new file mode 100644 index 0000000000..a46f757503 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/pom.xml @@ -0,0 +1,81 @@ +<?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> + + <parent> + <groupId>org.apache.tuscany.sca.services.containers</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>ruby</artifactId> + <name>Apache Tuscany Ruby Container</name> + <description>Apache Tuscany Ruby Container</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.jruby</groupId> + <artifactId>jruby</artifactId> + <version>0.9.1</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>wsdl</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>test</artifactId> + <version>${sca.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymockclassextension</artifactId> + </dependency> + <dependency> + <groupId>cglib</groupId> + <artifactId>cglib-nodep</artifactId> + <version>2.1_3</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-api</artifactId> + </dependency> + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-impl</artifactId> + </dependency> + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponent.java new file mode 100644 index 0000000000..7a244b828c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponent.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.container.ruby; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.container.ruby.rubyscript.RubyScript; +import org.apache.tuscany.container.ruby.rubyscript.RubyScriptInstance; +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.TargetException; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.extension.AtomicComponentExtension; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; + +/** + * The Ruby component implementation. + */ +public class RubyComponent extends AtomicComponentExtension { + + private final List<Class<?>> services; + + private final Map<String, Object> properties; + + private RubyScript rubyScript; + + private String rubyClassName; + + public RubyComponent(String name, + RubyScript rubyScript, + String rubyClassName, + List<Class<?>> services, + Map<String, Object> propValues, + CompositeComponent parent, + ScopeContainer scopeContainer, + WireService wireService, + WorkContext workContext) { + super(name, parent, scopeContainer, wireService, workContext, null, 0); + + this.rubyScript = rubyScript; + this.rubyClassName = rubyClassName; + this.services = services; + this.scope = scopeContainer.getScope(); + //this.properties = new HashMap<String, Object>(); + this.properties = propValues; + } + + public Object createInstance() throws ObjectCreationException { + + Map<String, Object> context = new HashMap<String, Object>(getProperties()); + + for (List<OutboundWire> referenceWires : getOutboundWires().values()) { + for (OutboundWire wire : referenceWires) { + Object wireProxy = wireService.createProxy(wire); + //since all types that may be used in the reference interface may not be known to Rhino + //using the wireProxy as is will fail result in type conversion exceptions in cases where + //Rhino does not know enough of the tpypes used. Hence introduce a interceptor proxy, + //with weak typing (java.lang.Object) so that Rhino's call to the proxy succeeds. Then + //within this interceptor proxy perform data mediations required to correctly call the + //referenced service. + Class<?> businessInterface = wire.getServiceContract().getInterfaceClass(); + RubyReferenceProxy interceptingProxy = new RubyReferenceProxy(businessInterface, + wireProxy, + rubyScript.getRubyEngine()); + context.put(wire.getReferenceName(), interceptingProxy.createProxy()); + } + } + + Object instance = rubyScript.createScriptInstance(context, rubyClassName); + + return instance; + } + + public TargetInvoker createTargetInvoker(String targetName, Operation operation) { + /*Method[] methods = operation.getServiceContract().getInterfaceClass().getMethods(); + Method method = findMethod(operation, + methods);*/ + return new RubyInvoker(operation.getName(), this, operation.getOutputType().getPhysical().getClass()); + } + + // TODO: move all the following up to AtomicComponentExtension? + + public List<Class<?>> getServiceInterfaces() { + return services; + } + + public Map<String, Object> getProperties() { + return properties; + } + + public RubyScriptInstance getTargetInstance() throws TargetException { + return (RubyScriptInstance) scopeContainer.getInstance(this); + } + + public Object getServiceInstance() throws TargetException { + return getServiceInstance(null); + } + + @SuppressWarnings("unchecked") + public Object getServiceInstance(String service) throws TargetException { + InboundWire wire = getInboundWire(service); + if (wire == null) { + TargetException e = new TargetException("ServiceDefinition not found"); // TODO better error message + e.setIdentifier(service); + throw e; + } + return wireService.createProxy(wire); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentBuilder.java new file mode 100644 index 0000000000..bdbbd1871c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentBuilder.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.ruby; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.container.ruby.rubyscript.RubyScript; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentBuilderExtension; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.PropertyValue; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceDefinition; + +/** + * Extension point for creating {@link RubyComponent}s from an assembly configuration + */ +public class RubyComponentBuilder extends ComponentBuilderExtension<RubyImplementation> { + + protected Class<RubyImplementation> getImplementationType() { + return RubyImplementation.class; + } + + @SuppressWarnings("unchecked") + public Component build(CompositeComponent parent, + ComponentDefinition<RubyImplementation> componentDefinition, + DeploymentContext deploymentContext) throws BuilderConfigException { + + String name = componentDefinition.getName(); + RubyImplementation implementation = componentDefinition.getImplementation(); + RubyComponentType componentType = implementation.getComponentType(); + + // get list of services provided by this component + Collection<ServiceDefinition> collection = componentType.getServices().values(); + List<Class<?>> services = new ArrayList<Class<?>>(collection.size()); + for (ServiceDefinition serviceDefinition : collection) { + services.add(serviceDefinition.getServiceContract().getInterfaceClass()); + } + + Map<String, Object> propertyValues = new Hashtable<String, Object>(); + Collection<PropertyValue<?>> propValueSettings = componentDefinition.getPropertyValues().values(); + for (PropertyValue propertyValue : propValueSettings) { + propertyValues.put(propertyValue.getName(), + propertyValue.getValueFactory().getInstance()); + } + + RubyScript rubyScript = implementation.getRubyScript(); + + // TODO: have ComponentBuilderExtension pass ScopeContainer in on build method? + ScopeContainer scopeContainer; + Scope scope = componentType.getLifecycleScope(); + if (Scope.MODULE == scope) { + scopeContainer = deploymentContext.getModuleScope(); + } else { + scopeContainer = scopeRegistry.getScopeContainer(scope); + } + + return new RubyComponent(name, + rubyScript, + implementation.getRubyClassName(), + services, + propertyValues, + parent, + scopeContainer, + wireService, + workContext); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentType.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentType.java new file mode 100644 index 0000000000..1b98cf86d6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentType.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.container.ruby; + +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceDefinition; + +public class RubyComponentType extends + ComponentType<ServiceDefinition, ReferenceDefinition, Property<?>> { + + private Scope lifecycleScope = Scope.MODULE; + + public RubyComponentType() { + } + + @SuppressWarnings("unchecked") + public RubyComponentType(ComponentType ct) { + // TODO: A bit hacky but this is so the non-Ruby .componentType side file can be used for now + setInitLevel(ct.getInitLevel()); + for (Object property : ct.getProperties().values()) { + add((Property) property); + } + for (Object reference : ct.getReferences().values()) { + add((ReferenceDefinition) reference); + } + for (Object service : ct.getServices().values()) { + add((ServiceDefinition) service); + } + } + + public Scope getLifecycleScope() { + return lifecycleScope; + } + + public void setLifecycleScope(Scope lifecycleScope) { + this.lifecycleScope = lifecycleScope; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentTypeLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentTypeLoader.java new file mode 100644 index 0000000000..6fc5f87c68 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyComponentTypeLoader.java @@ -0,0 +1,118 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.ruby; + +import java.net.URL; + +import org.apache.tuscany.container.ruby.rubyscript.RubySCAConfig; +import org.apache.tuscany.container.ruby.rubyscript.RubyScript; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentTypeLoaderExtension; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.apache.tuscany.spi.model.ComponentType; + +/** + * @version $Rev$ $Date$ + */ +public class RubyComponentTypeLoader extends ComponentTypeLoaderExtension<RubyImplementation> { + + private JavaInterfaceProcessorRegistry processorRegistry; + + public RubyComponentTypeLoader(@Autowire + JavaInterfaceProcessorRegistry processorRegistry) { + this.processorRegistry = processorRegistry; + } + + @Override + protected Class<RubyImplementation> getImplementationClass() { + return RubyImplementation.class; + } + + protected RubyComponentType loadByIntrospection(CompositeComponent parent, + RubyImplementation implementation, + DeploymentContext deploymentContext) throws + MissingResourceException, + InvalidServiceContractException { + + RubyScript rubyScript = implementation.getRubyScript(); + RubySCAConfig scaConfig = rubyScript.getSCAConfig(); + if (!scaConfig.hasSCAConfig()) { + throw new IllegalArgumentException( + "must use either .componentType side file or Ruby Global variable $SCA definition"); + } + + // FIXME this should be a system service, not instantiated here + RubyComponentType componentType = new RubyIntrospector(null, processorRegistry) + .introspectScript(scaConfig, rubyScript.getClassLoader()); + + return componentType; + } + + protected String getResourceName(RubyImplementation implementation) { + return implementation.getRubyScript().getScriptName(); + } + + // TODO: must be possible to move all the following up in to ComponentTypeLoaderExtension + + public void load(CompositeComponent parent, + RubyImplementation implementation, + DeploymentContext deploymentContext) throws LoaderException { + + URL resource = implementation.getRubyScript().getClassLoader().getResource(getSideFileName(implementation)); + RubyComponentType componentType; + if (resource == null) { + try { + componentType = loadByIntrospection(parent, implementation, deploymentContext); + } catch (InvalidServiceContractException e) { + throw new LoaderException("Invalid service contract", e); + } + } else { + componentType = loadFromSidefile(resource, deploymentContext); + } + + implementation.setComponentType(componentType); + + + } + + protected RubyComponentType loadFromSidefile(URL url, DeploymentContext deploymentContext) throws LoaderException { + ComponentType ct = loaderRegistry.load(null, + url, + ComponentType.class, + deploymentContext); + RubyComponentType jsct = new RubyComponentType(ct); + return jsct; + } + + private String getSideFileName(RubyImplementation implementation) { + String baseName = getResourceName(implementation); + int lastDot = baseName.lastIndexOf('.'); + if (lastDot != -1) { + baseName = baseName.substring(0, + lastDot); + } + return baseName + ".componentType"; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyImplementation.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyImplementation.java new file mode 100644 index 0000000000..6f07399d0a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyImplementation.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.container.ruby; + +import org.apache.tuscany.container.ruby.rubyscript.RubyScript; +import org.apache.tuscany.spi.model.AtomicImplementation; + +/** + * Model object for a JavaScript implementation. + */ +public class RubyImplementation extends AtomicImplementation<RubyComponentType> { + + private RubyScript rubyScript; + + private String rubyClassName; + + public String getRubyClassName() { + return rubyClassName; + } + + public void setRubyClassName(String rubyClassName) { + this.rubyClassName = rubyClassName; + } + + public RubyScript getRubyScript() { + return rubyScript; + } + + public void setRubyScript(RubyScript rubyScript) { + this.rubyScript = rubyScript; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyImplementationLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyImplementationLoader.java new file mode 100644 index 0000000000..322e3d84e8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyImplementationLoader.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.ruby; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.URL; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.container.ruby.rubyscript.RubyScript; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.osoa.sca.annotations.Constructor; + +/** + * Loader for handling JavaScript <js:implementation.js> elements. + */ +public class RubyImplementationLoader extends LoaderExtension<RubyImplementation> { + private static final QName IMPLEMENTATION_RUBY = new QName( + "http://incubator.apache.org/tuscany/xmlns/container/rb/1.0-incubator-M2", "implementation.rb"); + + @Constructor({"registry"}) + public RubyImplementationLoader(@Autowire + LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return IMPLEMENTATION_RUBY; + } + + public RubyImplementation load(CompositeComponent parent, + XMLStreamReader reader, + DeploymentContext deploymentContext) throws XMLStreamException, + LoaderException { + + String script = reader.getAttributeValue(null, + "script"); + String rubyClassName = reader.getAttributeValue(null,"class"); + + if ( script == null ) { + throw new MissingResourceException("No script supplied"); + } + + ClassLoader cl = deploymentContext.getClassLoader(); + String source = loadSource(cl, + script); + + LoaderUtil.skipToEndElement(reader); + + RubyImplementation implementation = new RubyImplementation(); + RubyScript rubyScript = new RubyScript(script, source, null, cl); + implementation.setRubyScript(rubyScript); + implementation.setRubyClassName(rubyClassName); + registry.loadComponentType(parent, + implementation, + deploymentContext); + return implementation; + } + + protected String loadSource(ClassLoader cl, String resource) throws LoaderException { + URL url = cl.getResource(resource); + if (url == null) { + throw new MissingResourceException(resource); + } + InputStream is; + try { + is = url.openStream(); + } catch (IOException e) { + MissingResourceException mre = new MissingResourceException(resource, e); + mre.setIdentifier(resource); + throw mre; + } + try { + Reader reader = new InputStreamReader(is, "UTF-8"); + char[] buffer = new char[1024]; + StringBuilder source = new StringBuilder(); + int count; + while ((count = reader.read(buffer)) > 0) { + source.append(buffer, + 0, + count); + } + return source.toString(); + } catch (IOException e) { + LoaderException le = new LoaderException(e); + le.setIdentifier(resource); + throw le; + } finally { + try { + is.close(); + } catch (IOException e) { + // ignore + } + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyIntrospector.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyIntrospector.java new file mode 100644 index 0000000000..d5ef41d835 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyIntrospector.java @@ -0,0 +1,173 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.ruby; + +import java.util.Iterator; +import java.util.Map; + +import javax.wsdl.Definition; +import javax.wsdl.PortType; +import javax.wsdl.WSDLException; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +import org.apache.tuscany.container.ruby.rubyscript.RubySCAConfig; +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistry; +import org.apache.tuscany.idl.wsdl.WSDLServiceContract; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.model.ServiceDefinition; + +/** + * Introspects JavaScript files for SCA configuration + */ +public class RubyIntrospector { + + private WSDLDefinitionRegistry wsdlRegistry; + private JavaInterfaceProcessorRegistry processorRegistry; + + public RubyIntrospector(@Autowire WSDLDefinitionRegistry wsdlRegistry, + @Autowire JavaInterfaceProcessorRegistry processorRegistry) { + this.wsdlRegistry = wsdlRegistry; + this.processorRegistry = processorRegistry; + } + + public RubyComponentType introspectScript(RubySCAConfig scaConfig, ClassLoader cl) + throws MissingResourceException, InvalidServiceContractException { + RubyComponentType componentType = new RubyComponentType(); + introspectJavaInterface(componentType, cl, scaConfig.getJavaInterface()); + introspectWSDLInterface(componentType, cl, scaConfig.getWSDLNamespace(), scaConfig.getWSDLPortType(), + scaConfig.getWSDLLocation()); + introspectReferences(componentType, cl, scaConfig.getReferences()); + introspectProperties(componentType, cl, scaConfig.getProperties()); + introspectScope(componentType, scaConfig.getScope()); + return componentType; + } + + private void introspectScope(RubyComponentType componentType, Scope scope) { + if (scope != null) { + componentType.setLifecycleScope(scope); + } + } + + @SuppressWarnings("unchecked") + private void introspectJavaInterface(ComponentType componentType, ClassLoader cl, String serviceClass) + throws MissingResourceException, InvalidServiceContractException { + if (serviceClass != null) { + ServiceDefinition service = new ServiceDefinition(); + try { + ServiceContract<?> sc = processorRegistry.introspect(Class.forName(serviceClass)); + service.setServiceContract(sc); + componentType.add(service); + } catch (ClassNotFoundException e) { + throw new MissingResourceException("Interface not found", e); + } + } + } + + @SuppressWarnings("unchecked") + private void introspectWSDLInterface(ComponentType componentType, ClassLoader cl, String wsdlNamespace, + String wsdlPortType, String wsdlLocation) { + if (wsdlNamespace == null && wsdlPortType == null && wsdlLocation == null) { + return; + } + + PortType portType = null; + if (wsdlLocation != null) { + portType = readWSDLPortType(wsdlNamespace, wsdlPortType, wsdlLocation, portType); + } else { + portType = getPortType(wsdlNamespace, wsdlPortType); + } + + ServiceDefinition service = new ServiceDefinition(); + WSDLServiceContract wsdlSC = new WSDLServiceContract(); + wsdlSC.setPortType(portType); + service.setServiceContract(wsdlSC); + componentType.add(service); + } + + private PortType readWSDLPortType(String wsdlNamespace, String wsdlPortType, String wsdlLocation, + PortType portType) { + Definition wsdlDefinition; + try { + WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + wsdlDefinition = reader.readWSDL(wsdlLocation.toString()); + } catch (WSDLException e) { + throw new RuntimeException(e); + + } + Map portTypes = wsdlDefinition.getPortTypes(); + for (Iterator i = portTypes.keySet().iterator(); i.hasNext();) { + QName portTypeQN = (QName) i.next(); + if (wsdlNamespace != null) { + if (!portTypeQN.getNamespaceURI().equals(wsdlNamespace)) { + continue; + } + } + if (wsdlPortType != null) { + if (!portTypeQN.getLocalPart().equals(wsdlPortType)) { + continue; + } + } + if (portType != null) { + throw new RuntimeException("multiple matching portTypes in wsdl: " + wsdlLocation); + } + portType = (PortType) portTypes.get(portTypeQN); + } + if (portType == null) { + throw new RuntimeException("portType not found in wsdl: " + wsdlLocation); + } + return portType; + } + + private PortType getPortType(String wsdlNamespace, String wsdlPortType) { + if (wsdlPortType == null) { + throw new IllegalArgumentException("must specify the wsdlPortType in script SCA config"); + } + PortType portType = null; + if (wsdlNamespace != null) { + QName portTypeQN = new QName(wsdlNamespace.toString(), wsdlPortType.toString()); + portType = wsdlRegistry.getPortType(portTypeQN); + if (portType == null) { + throw new IllegalArgumentException("no WSDL registered for portType: " + portTypeQN); + } + } else { + // wsdlRegistry.getPortType(wsdlPortType.toString()); + if (portType == null) { + throw new IllegalArgumentException("no WSDL registered for portType:" + wsdlPortType); + } + } + return portType; + } + + + private void introspectProperties(ComponentType componentType, ClassLoader cl, Map properties) { + } + + private void introspectReferences(ComponentType componentType, ClassLoader cl, Map references) { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyInvoker.java new file mode 100644 index 0000000000..a40f04612e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyInvoker.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.container.ruby; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.tuscany.container.ruby.rubyscript.RubyScriptInstance; +import org.apache.tuscany.spi.extension.TargetInvokerExtension; + +/** + * Dispatches to a JavaScript implementation instance + * + * @version $$Rev$$ $$Date$$ + */ +public class RubyInvoker extends TargetInvokerExtension { + + private RubyComponent context; + + private String functionName; + + private Class returnType; + + public RubyInvoker(String functionName, RubyComponent context, Class returnType) { + this.functionName = functionName; + this.context = context; + this.returnType = returnType; + } + + /** + * Invokes a function on a script instance + */ + public Object invokeTarget(final Object payload) throws InvocationTargetException { + RubyScriptInstance target = context.getTargetInstance(); + return target.invokeFunction(functionName, + (Object[]) payload, + returnType); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyRefInvocInterceptor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyRefInvocInterceptor.java new file mode 100644 index 0000000000..bf62d1fcab --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyRefInvocInterceptor.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.container.ruby;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+
+import org.jruby.IRuby;
+import org.jruby.RubyObject;
+import org.jruby.javasupport.JavaUtil;
+
+/**
+ * This Interceptor encasulates the data mediation required by the JavaScriptReferenceProxy. The
+ * invocation handler of this class traps the javascript reference calls, performs data mediation
+ * and calls then calls the actual referred service. This classes implementation is subject to
+ * review and change when the DataMediation infrastructure of Tuscany is ready.
+ *
+ */
+public class RubyRefInvocInterceptor implements InvocationHandler {
+ private Object actualProxy;
+
+ private Class wireInterface;
+
+ private IRuby rubyEngine;
+
+ RubyRefInvocInterceptor(Object wireProxy, Class wireIfc, IRuby rubyEng) {
+ this.actualProxy = wireProxy;
+ this.wireInterface = wireIfc;
+ this.rubyEngine = rubyEng;
+ }
+
+ public Object invoke(Object arg0, Method method, Object[] args) throws Throwable {
+ if ( method.getName().equals("hashCode"))
+ return new Integer(1);
+
+ Method invokedMethod = getInvokedMethod(method.getName());
+ Object[] tranformedArgs = new Object[args.length];
+ for (int count = 0; count < args.length; ++count) {
+ tranformedArgs[count] = fromRubyToJava(invokedMethod.getParameterTypes()[count], args[count]);
+ }
+
+ Object response = invokedMethod.invoke(actualProxy, tranformedArgs);
+ response = fromJavaToRuby(response);
+ return response;
+ }
+
+ private Method getInvokedMethod(String methodName) {
+ Method[] methods = wireInterface.getMethods();
+
+ for (int count = 0; count < methods.length; ++count) {
+ if (methods[count].getName().equals(methodName)) {
+ return methods[count];
+ }
+ }
+ throw new RuntimeException("Unable to find invocation method");
+ }
+
+ protected Object fromRubyToJava(Class reqArgType, Object rubyArg) throws Exception {
+ Object javaArg = null;
+
+ //for known cases the JRuby runtime handles the conversion before calling the Java objects
+ //so nothing to do. When it cannot convert it simply passed the instance of RubyObject
+ if ( rubyArg instanceof RubyObject ) {
+ //need to deal with this
+ } else {
+ javaArg = rubyArg;
+ }
+
+ return javaArg;
+ }
+
+ protected Object fromJavaToRuby(Object retVal) throws RuntimeException {
+ Object rubyRetVal = JavaUtil.convertJavaToRuby(rubyEngine, retVal, retVal.getClass());
+ return rubyRetVal;
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyReferenceProxy.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyReferenceProxy.java new file mode 100644 index 0000000000..4d91194484 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/RubyReferenceProxy.java @@ -0,0 +1,127 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.ruby;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+import org.jruby.IRuby;
+import org.jruby.RubyException;
+
+import net.sf.cglib.asm.ClassWriter;
+import net.sf.cglib.asm.CodeVisitor;
+import net.sf.cglib.asm.Constants;
+import net.sf.cglib.asm.Type;
+
+/**
+ * This is a proxy that will mediate reference calls from the JavaScript. The mediation code here will be reviewed when the DataMediation
+ * infrastructure is ready. This proxy assmes that there is no verloading of service methods on the reference interface i.e. there are no two service
+ * methods that have the same method name or operation name.
+ */
+public class RubyReferenceProxy {
+
+ private Class interfaze;
+
+ private Object wireProxy;
+
+ private IRuby rubyEngine;
+
+ public RubyReferenceProxy(Class interfaze, Object wireProxy, IRuby rubyEng) {
+ this.interfaze = interfaze;
+ this.wireProxy = wireProxy;
+ this.rubyEngine = rubyEng;
+ }
+
+ public Object createProxy() {
+ try {
+ GenericProxyClassLoader classloader = new GenericProxyClassLoader();
+ final byte[] byteCode = generateGenericInterface(interfaze);
+
+ Class genericInterface = classloader.defineClass(byteCode);
+ InvocationHandler proxyHandler = new RubyRefInvocInterceptor(wireProxy, interfaze, rubyEngine);
+ // return genericInterface.cast(Proxy.newProxyInstance(classloader, new Class[]{genericInterface}, proxyHandler));
+ return Proxy.newProxyInstance(classloader,
+ new Class[]{genericInterface},
+ proxyHandler);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ private static byte[] generateGenericInterface(Class serviceInterface) {
+ String interfazeName = serviceInterface.getCanonicalName();
+ ClassWriter cw = new ClassWriter(false);
+
+ cw.visit(Constants.V1_5,
+ Constants.ACC_PUBLIC + Constants.ACC_ABSTRACT + Constants.ACC_INTERFACE,
+ interfazeName.replace('.',
+ '/'),
+ "java/lang/Object",
+ null,
+ serviceInterface.getSimpleName() + ".java");
+
+ StringBuffer argsAndReturn = new StringBuffer("(");
+ Method[] methods = serviceInterface.getMethods();
+ for (int count = 0; count < methods.length; ++count) {
+ argsAndReturn = new StringBuffer("(");
+ Class[] paramTypes = methods[count].getParameterTypes();
+ Class returnType = methods[count].getReturnType();
+
+ for (int paramCount = 0; paramCount < paramTypes.length; ++paramCount) {
+ argsAndReturn.append(Type.getType(Object.class));
+ }
+ argsAndReturn.append(")");
+ argsAndReturn.append(Type.getType(Object.class));
+
+ Class[] exceptionTypes = methods[count].getExceptionTypes();
+ String[] exceptions = new String[exceptionTypes.length];
+ for (int excCount = 0; excCount < exceptionTypes.length; ++excCount) {
+ exceptions[excCount] = exceptionTypes[excCount].getName();
+ exceptions[excCount] = exceptions[excCount].replace('.',
+ '/');
+ }
+
+ CodeVisitor cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_ABSTRACT,
+ methods[count].getName(),
+ argsAndReturn.toString(),
+ exceptions,
+ null);
+ cw.visitEnd();
+ }
+
+ cw.visitEnd();
+
+ return cw.toByteArray();
+ }
+
+ private class GenericProxyClassLoader extends ClassLoader {
+ public Class defineClass(byte[] byteArray) {
+ try {
+ return defineClass(null,
+ byteArray,
+ 0,
+ byteArray.length);
+ } catch (Throwable e) {
+ return null;
+ }
+ }
+
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubySCAConfig.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubySCAConfig.java new file mode 100644 index 0000000000..4d14d8a56a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubySCAConfig.java @@ -0,0 +1,159 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.ruby.rubyscript; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.model.Scope; +import org.jruby.RubyHash; +import org.jruby.RubyObject; +import org.jruby.internal.runtime.GlobalVariables; +import org.jruby.runtime.builtin.IRubyObject; + +/** + * Represents the variable defining the SCA aspects of the script + * <code> + * SCA = { + * javaInterface : "my.pkg.ClassName", + * wsdlPortType : "wsdlPortTypeName", + * wsdlNameSpace : "http://my.namespace.com", + * wsdlLocation : "\wsdl\mywsdl.txt", + * properties : { "foo" : ["java.lang.String", "defaultValue"],}, + * references : {}, + * scope : 'stateless'|'request'|'conversational'|'composite', + * } + * </code> + * The config must define the service with either javaInterface or wsdl. When + * using wsdl the three parameters are optional. If wsdlLocation is used that is the + * WSDL document used, and the namespace and portType parameters are only required if + * the WSDL definition defines multiple portTypes. + */ +public class RubySCAConfig { + + private boolean hasSCAConfig; + + private String javaInterface; + + private String wsdlLocation; + + private String wsdlNamespace; + + private String wsdlPortType; + + private Map properties; + + private Map references; + + private Scope scope; + + public RubySCAConfig(GlobalVariables globalVariables) { + IRubyObject rubyObject = globalVariables.get("$SCA"); + if (rubyObject != null && !rubyObject.isNil()) { + hasSCAConfig = true; + RubyHash scaVar = (RubyHash) rubyObject; + Object o = scaVar.get("javaInterface"); + if ( o != null ) { + this.javaInterface = o.toString(); + } + o = scaVar.get("wsdlLocation"); + if (o != null ) { + this.wsdlLocation = o.toString(); + } + o = scaVar.get("wsdlPortType"); + if (o != null ) { + this.wsdlPortType = o.toString(); + } + o = scaVar.get("wsdlNamespace"); + if (o != null ) { + this.wsdlNamespace = o.toString(); + } + if (javaInterface != null) { + if (wsdlLocation != null || wsdlPortType != null || wsdlNamespace != null) { + throw new IllegalArgumentException("script SCA config defines both Java and WSDL service interface"); + } + } else { + if (wsdlLocation == null && wsdlPortType == null && wsdlNamespace == null) { + throw new IllegalArgumentException("script SCA config must define either Java or WSDL service interface"); + } + } + + this.properties = new HashMap(); + o = scaVar.get("properties"); + if (o != null ) { + // TODO parse properties + } + + this.references = new HashMap(); + o = scaVar.get("references"); + if (o != null ) { + // TODO parse references + } + + o = scaVar.get("scope"); + if (o != null ) { + if ("stateless".equalsIgnoreCase(String.valueOf(o))) { + this.scope = Scope.STATELESS; + } else if ("request".equalsIgnoreCase(String.valueOf(o))) { + this.scope = Scope.REQUEST; + } else if ("conversational".equalsIgnoreCase(String.valueOf(o))) { + this.scope = Scope.SESSION; // TODO: where's CONVERSATIONAL? + } else if ("composite".equalsIgnoreCase(String.valueOf(o))) { + this.scope = Scope.MODULE; // TODO: composite = MODULE for now? + } else { + throw new IllegalArgumentException("invalid scope value: " + o); + } + } + + } + } + + public boolean hasSCAConfig() { + return hasSCAConfig; + } + + public String getJavaInterface() { + return javaInterface; + } + + public Map getProperties() { + return properties; + } + + public Map getReferences() { + return references; + } + + public String getWSDLLocation() { + return wsdlLocation; + } + + public String getWSDLNamespace() { + return wsdlNamespace; + } + + public String getWSDLPortType() { + return wsdlPortType; + } + + public Scope getScope() { + return scope; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyScript.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyScript.java new file mode 100644 index 0000000000..87d995eabd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyScript.java @@ -0,0 +1,160 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.ruby.rubyscript; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Vector; + +import org.jruby.IRuby; +import org.jruby.RubyString; +import org.jruby.javasupport.JavaEmbedUtils; +import org.jruby.javasupport.JavaUtil; +import org.jruby.runtime.builtin.IRubyObject; + +/** + * A RhinoScript represents a compiled JavaScript script + */ +public class RubyScript { + protected final String NEW = ".new"; + protected final String EQUAL = "="; + + protected String scriptName; + + protected String script; + + protected Map<String, Class> responseClasses; + + protected ClassLoader classLoader; + + private IRuby rubyEngine = JavaEmbedUtils.initialize(new Vector()); + + /** + * Create a new RubyScript. + * + * @param scriptName + * the name of the script. Can be anything, only used in messages to identify the script + * @param script + * the complete script + */ + public RubyScript(String scriptName, String script) { + this(scriptName, script, (Map) null, null); + } + + /** + * Create a new RubyScript. + * + * @param scriptName + * the name of the script. Can be anything, only used in messages to identify the script + * @param script + * the complete script + * @param context + * name-value pairs that are added in to the scope where the script is compiled. May be null. The value objects are made available to + * the script by using a variable with the name. + * @param classLoader + * the ClassLoader to be used to locate any user Java classes used in the script + */ + public RubyScript(String scriptName, String script, Map context, ClassLoader classLoader) { + this.scriptName = scriptName; + this.script = script; + this.responseClasses = new HashMap<String, Class>(); + this.classLoader = classLoader; + rubyEngine.loadScript((RubyString) JavaUtil.convertJavaToRuby(rubyEngine, + "MyScript.rb", + String.class), + (RubyString) JavaUtil.convertJavaToRuby(rubyEngine, + this.script, + String.class), + false); + } + + /** + * Create a new invokeable instance of the script + * + * @return a IRubyObject + */ +public RubyScriptInstance createScriptInstance(Map<String, Object> context, String rubyClassName) { + if ( rubyClassName == null ) { + return new RubyScriptInstance(rubyEngine.evalScript(script), responseClasses); + } + else { + IRubyObject rubyObject = rubyEngine.evalScript(rubyClassName + NEW); + + Iterator<String> keyIterator = context.keySet().iterator(); + String key = null; + Object value = null; + while ( keyIterator.hasNext()) { + key = keyIterator.next(); + value = JavaUtil.convertJavaToRuby(rubyEngine, + context.get(key), + context.get(key).getClass()); + + JavaEmbedUtils.invokeMethod(rubyEngine, + rubyObject, + key + EQUAL, + new Object[]{value}, null); + } + + return new RubyScriptInstance(rubyObject, responseClasses); + } + } + public String getScript() { + return script; + } + + public String getScriptName() { + return scriptName; + } + + public Map<String, Class> getResponseClasses() { + return responseClasses; + } + + public ClassLoader getClassLoader() { + return classLoader; + } + + /** + * Set the Java type of a response value. JavaScript is dynamically typed so Rhino cannot always work out what the intended Java type of a + * response should be, for example should the statement "return 42" be a Java int, or Integer or Double etc. When Rhino can't determine the type + * it will default to returning a String, using this method enables overriding the Rhino default to use a specific Java type. + */ + public void setResponseClass(String functionName, Class responseClasses) { + this.responseClasses.put(functionName, + responseClasses); + } + + public RubySCAConfig getSCAConfig() { + return new RubySCAConfig(rubyEngine.getGlobalVariables()); + } + + public void setScript(String script) { + this.script = script; + } + + public IRuby getRubyEngine() { + return rubyEngine; + } + + public void setRubyEngine(IRuby rubyEngine) { + this.rubyEngine = rubyEngine; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyScriptInstance.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyScriptInstance.java new file mode 100644 index 0000000000..2d93c57fc9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyScriptInstance.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.container.ruby.rubyscript; + +import java.util.HashMap; +import java.util.Map; + +import org.jruby.javasupport.JavaEmbedUtils; +import org.jruby.runtime.builtin.IRubyObject; + +/** + * An invokeable instance of a JavaScript script. + */ +public class RubyScriptInstance { + + private IRubyObject rubyInstance; + + private Map<String, Class> responseClasses; + + public RubyScriptInstance(IRubyObject rubyInstance, Map<String, Class> responseClasses) { + this.rubyInstance = rubyInstance; + this.responseClasses = responseClasses; + if (this.responseClasses == null) { + this.responseClasses = new HashMap<String, Class>(); + } + } + + public Object invokeFunction(String functionName, Object[] args, Class returnType) { + Object[] rubyArgs = RubyUtils.fromJavaToRuby(rubyInstance.getRuntime(), args); + + Object rubyResponse = JavaEmbedUtils.invokeMethod(rubyInstance.getRuntime(), + rubyInstance, + functionName, + rubyArgs, + returnType); + Object response = RubyUtils.fromRubyToJava(rubyInstance.getRuntime(), + returnType, + rubyResponse); + return response; + } + + + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyUtils.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyUtils.java new file mode 100644 index 0000000000..c19f233b94 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/java/org/apache/tuscany/container/ruby/rubyscript/RubyUtils.java @@ -0,0 +1,71 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.ruby.rubyscript;
+
+import java.io.ByteArrayInputStream;
+
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.util.StAXUtils;
+import org.jruby.IRuby;
+import org.jruby.RubyObject;
+import org.jruby.javasupport.JavaUtil;
+
+/**
+ * @author administrator
+ *
+ */
+public class RubyUtils {
+ public static Object fromRubyToJava(IRuby rubyEngine, Class reqArgType, Object rubyArg) {
+ Object javaArg = null;
+
+ //for known cases the JRuby runtime handles the conversion before calling the Java objects
+ //so nothing to do. When it cannot convert it simply passed the instance of RubyObject
+ if ( rubyArg instanceof RubyObject ) {
+ //need to deal with this
+ } else {
+ javaArg = rubyArg;
+ }
+
+ return javaArg;
+ }
+
+ public static Object[] fromJavaToRuby(IRuby rubyEngine, Object[] arg) {
+ Object[] jsArgs;
+ if (arg == null) {
+ jsArgs = new Object[0];
+ } else {
+ jsArgs = new Object[arg.length];
+ for (int i = 0; i < jsArgs.length; i++) {
+ jsArgs[i] = fromJavaToRuby(rubyEngine, arg[i]);
+ }
+ }
+
+ return jsArgs;
+ }
+
+ public static Object fromJavaToRuby(IRuby rubyEngine, Object javaObj) {
+ Object rubyObj = JavaUtil.convertJavaToRuby(rubyEngine, javaObj, javaObj.getClass());
+ return rubyObj;
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..7a329afb7a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,46 @@ +<?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. +--> +<!-- + Ruby configuration for the launcher environment. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + + name="org.apache.tuscany.launcher.RubyImplementation"> + + <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <group>org.apache.tuscany.sca.services.containers</group> + <name>ruby</name> + <version>1.0-incubator-M2-SNAPSHOT</version> + </dependency> + + <component name="ruby.implementationLoader"> + <system:implementation.system class="org.apache.tuscany.container.ruby.RubyImplementationLoader"/> + </component> + + <component name="ruby.componentTypeLoader"> + <system:implementation.system class="org.apache.tuscany.container.ruby.RubyComponentTypeLoader"/> + </component> + + <component name="ruby.componentBuilder"> + <system:implementation.system class="org.apache.tuscany.container.ruby.RubyComponentBuilder"/> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/resources/META-INF/sca/ruby.system.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/resources/META-INF/sca/ruby.system.scdl new file mode 100644 index 0000000000..686e1ea308 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/main/resources/META-INF/sca/ruby.system.scdl @@ -0,0 +1,40 @@ +<?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.
+-->
+<!--
+ Ruby configuration for the launcher environment.
+-->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0"
+ xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+
+ name="org.apache.tuscany.launcher.RubyImplementation">
+
+ <component name="ruby.implementationLoader">
+ <system:implementation.system class="org.apache.tuscany.container.ruby.RubyImplementationLoader"/>
+ </component>
+
+ <component name="ruby.componentTypeLoader">
+ <system:implementation.system class="org.apache.tuscany.container.ruby.RubyComponentTypeLoader"/>
+ </component>
+
+ <component name="ruby.componentBuilder">
+ <system:implementation.system class="org.apache.tuscany.container.ruby.RubyComponentBuilder"/>
+ </component>
+
+</composite>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/helloworld/HelloWorldService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/helloworld/HelloWorldService.java new file mode 100644 index 0000000000..7e99f6f720 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/helloworld/HelloWorldService.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package helloworld; + + +public interface HelloWorldService { + String sayHello(String s); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/helloworld/HelloWorldServiceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/helloworld/HelloWorldServiceImpl.java new file mode 100644 index 0000000000..be804d3540 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/helloworld/HelloWorldServiceImpl.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package helloworld; + +import org.osoa.sca.annotations.Property; + + +public class HelloWorldServiceImpl implements HelloWorldService { + + @Property + public String greeting = "Default hello"; + + public String getGreeting() { + return greeting; + } + + + public void setGreeting(String greeting) { + this.greeting = greeting; + } + + public String sayHello(String s) { + //return greeting + s + " from the JavaWorld!"; + return greeting + " from Java Reference " + s ; //+ " from " + helloSayer.firstName + " " + helloSayer.lastName; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/RubyImplementationLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/RubyImplementationLoaderTestCase.java new file mode 100644 index 0000000000..289a187461 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/RubyImplementationLoaderTestCase.java @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.ruby; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.MissingResourceException; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; + +/** + * Tests for RubyImplementationLoader + */ +public class RubyImplementationLoaderTestCase extends TestCase { + private CompositeComponent parent; + + private XMLStreamReader reader; + + private DeploymentContext deploymentContext; + + private ClassLoader classLoader; + + private LoaderRegistry registry; + + private RubyImplementationLoader loader; + + public void testNoScriptAttribute() throws LoaderException, XMLStreamException { + expect(reader.getAttributeValue(null, "script")).andReturn(null); + expect(reader.getAttributeValue(null, "class")).andReturn(null); + replay(reader); + replay(deploymentContext); + + try { + loader.load(parent, reader, deploymentContext); + fail(); + } catch (MissingResourceException e) { + // ok + } + verify(reader); + verify(deploymentContext); + } + + public void testNoScriptPresent() throws LoaderException, XMLStreamException { + expect(reader.getAttributeValue(null, "script")).andReturn("foo.groovy"); + expect(reader.getAttributeValue(null, "class")).andReturn(null); + expect(deploymentContext.getClassLoader()).andReturn(classLoader); + + replay(reader); + replay(deploymentContext); + + RubyImplementationLoader mockLoader = new RubyImplementationLoader(registry) { + protected String loadSource(ClassLoader cl, String resource) throws LoaderException { + assertSame(classLoader, cl); + assertEquals("foo.groovy", resource); + throw new MissingResourceException(resource); + } + }; + try { + mockLoader.load(parent, reader, deploymentContext); + fail(); + } catch (MissingResourceException e) { + assertEquals("foo.groovy", e.getMessage()); + } + verify(reader); + verify(deploymentContext); + } + + public void testLoadScript() throws LoaderException { + String script = + loader.loadSource(getClass().getClassLoader(), "org/apache/tuscany/container/ruby/mock/test.rb"); + assertEquals("//Test Script", script); + } + + protected void setUp() throws Exception { + super.setUp(); + registry = createMock(LoaderRegistry.class); + loader = new RubyImplementationLoader(registry); + + parent = createMock(CompositeComponent.class); + reader = createMock(XMLStreamReader.class); + deploymentContext = createMock(DeploymentContext.class); + classLoader = createMock(ClassLoader.class); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/RubyScriptIntrospectorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/RubyScriptIntrospectorTestCase.java new file mode 100644 index 0000000000..4f4869355d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/RubyScriptIntrospectorTestCase.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.container.ruby; + +import helloworld.HelloWorldService; + +import java.io.IOException; +import java.net.URL; +import java.util.Map; + +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.tuscany.container.ruby.rubyscript.RubySCAConfig; +import org.apache.tuscany.container.ruby.rubyscript.RubyScript; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistryImpl; +import org.apache.tuscany.idl.wsdl.WSDLServiceContract; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.model.ServiceDefinition; + +public class RubyScriptIntrospectorTestCase extends TestCase { + + private static final WSDLDefinitionRegistryImpl.Monitor NULL_MONITOR = new WSDLDefinitionRegistryImpl.Monitor() { + public void readingWSDL(String namespace, URL location) { + } + + public void cachingDefinition(String namespace, URL location) { + } + }; + + public void testJavaInterface() throws MissingResourceException, + InvalidServiceContractException { + RubyScript rs = new RubyScript("javaInterfaceTest", + "$SCA = { 'javaInterface' => 'helloworld.HelloWorldService'}", + null, + getClass().getClassLoader()); + RubySCAConfig scaConfig = new RubySCAConfig(rs.getRubyEngine().getGlobalVariables()); + RubyIntrospector introspector = new RubyIntrospector(null, + new JavaInterfaceProcessorRegistryImpl()); + ComponentType comonentType = introspector.introspectScript(scaConfig, + rs.getClassLoader()); + assertNotNull(comonentType); + Map services = comonentType.getServices(); + assertEquals(1, + services.size()); + ServiceDefinition serviceDefinition = (ServiceDefinition) services.values() + .iterator() + .next(); + ServiceContract serviceContract = serviceDefinition.getServiceContract(); + assertTrue(serviceContract instanceof JavaServiceContract); + JavaServiceContract javaServiceContract = (JavaServiceContract) serviceContract; + assertEquals(HelloWorldService.class, + javaServiceContract.getInterfaceClass()); + } + + public void testWSDLLocation() throws WSDLException { + // RhinoScript rs = new RhinoScript("wsdlLocation", + // "SCA = { wsdlLocation : 'src/test/resources/org/apache/tuscany/container/javascript/rhino/helloworld.wsdl',};", null, getClass() + // .getClassLoader()); + // RhinoSCAConfig scaConfig = new RhinoSCAConfig(rs.getScriptScope()); + // JavaScriptIntrospector introspector = new JavaScriptIntrospector(null); + // ComponentType comonentType = introspector.introspectScript(scaConfig, rs.getClassLoader()); + // assertNotNull(comonentType); + // Map services = comonentType.getServices(); + // assertEquals(1, services.size()); + // ServiceDefinition serviceDefinition = (ServiceDefinition) services.values().iterator().next(); + // ServiceContract serviceContract = serviceDefinition.getServiceContract(); + // assertTrue(serviceContract instanceof WSDLServiceContract); + // WSDLServiceContract wsdlServiceContract = (WSDLServiceContract) serviceContract; + // assertEquals(new QName("http://helloworld", "HelloWorld"), wsdlServiceContract.getPortType().getQName()); + } + + public void testWSDLPortType() throws WSDLException, + IOException, + MissingResourceException, + InvalidServiceContractException { + RubyScript rs = new RubyScript("wsdlPortType", + "$SCA = { 'wsdlPortType' => 'HelloWorld', 'wsdlNamespace' => 'http://helloworld'}", + null, + getClass().getClassLoader()); + RubySCAConfig scaConfig = new RubySCAConfig(rs.getRubyEngine().getGlobalVariables()); + + WSDLDefinitionRegistryImpl wsdlReg = new WSDLDefinitionRegistryImpl(); + wsdlReg.setMonitor(NULL_MONITOR); + URL wsdlURL = getClass().getClassLoader() + .getResource("org/apache/tuscany/container/ruby/jruby/helloworld.wsdl"); + wsdlReg.loadDefinition("http://helloworld", + wsdlURL); + + RubyIntrospector introspector = new RubyIntrospector(wsdlReg, + new JavaInterfaceProcessorRegistryImpl()); + ComponentType comonentType = introspector.introspectScript(scaConfig, + rs.getClassLoader()); + assertNotNull(comonentType); + Map services = comonentType.getServices(); + assertEquals(1, + services.size()); + ServiceDefinition serviceDefinition = (ServiceDefinition) services.values() + .iterator() + .next(); + ServiceContract serviceContract = serviceDefinition.getServiceContract(); + assertTrue(serviceContract instanceof WSDLServiceContract); + WSDLServiceContract wsdlServiceContract = (WSDLServiceContract) serviceContract; + assertEquals(new QName("http://helloworld", "HelloWorld"), + wsdlServiceContract.getPortType().getQName()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/ScriptInvokeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/ScriptInvokeTestCase.java new file mode 100644 index 0000000000..c83605eecb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/ScriptInvokeTestCase.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.ruby; + +import junit.framework.TestCase; + +import org.apache.tuscany.container.ruby.rubyscript.RubyScript; + +/** + * Tests for invoker JavaScriptComponents + */ +public class ScriptInvokeTestCase extends TestCase { + + private static final String SCRIPT = "def greet(name) \n return name \n end \n"; + + private RubyScript rubyScript; + + /** + * Tests the invocation of a Groovy "script" as opposed to a class + */ + public void testBasicScriptInvocation() throws Exception { +// ModuleScopeContainer scope = new ModuleScopeContainer(null); +// scope.start(); +// List<Class<?>> services = new ArrayList<Class<?>>(); +// services.add(Greeting.class); +// RubyComponent<Greeting> context = new RubyComponent<Greeting>("source", rhinoScript, services, new HashMap<String, Object>(), +// null, scope, ArtifactFactory.createWireService(), null); +// scope.register(context); +// Greeting object = (Greeting) context.getServiceInstance(); +// assertEquals("foo", object.greet("foo")); +// scope.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + rubyScript = new RubyScript("test", SCRIPT); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/WireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/WireTestCase.java new file mode 100644 index 0000000000..3794eb82f7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/WireTestCase.java @@ -0,0 +1,186 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.ruby; + +import static org.easymock.EasyMock.reportMatcher; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.apache.tuscany.container.ruby.mock.Greeting; +import org.apache.tuscany.container.ruby.rubyscript.RubyScript; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.spi.model.DataType; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.test.ArtifactFactory; +import org.easymock.IArgumentMatcher; + +/** + * Tests for JavaScript component wiring + */ +public class WireTestCase extends TestCase { + + private static final String SCRIPT = " def setWire(ref)\n" + " wire = ref\n" + + "end \n" + " def greet(name)\n" + " return wire.greet(name) \n" + + " end\n"; + + private static final String SCRIPT2 = " def greet(name)\n" + " return name \n" + + "end \n"; + + private RubyScript implClass1; + + private RubyScript implClass2; + + /** + * Tests a basic invocation down a source wire + */ + public void testReferenceWireInvocation() throws Exception { + // ModuleScopeContainer scope = new ModuleScopeContainer(null); + // scope.start(); + // + // List<Class<?>> services = new ArrayList<Class<?>>(); + // services.add(Greeting.class); + // JavaScriptComponent<Greeting> context = new JavaScriptComponent<Greeting>("source", implClass1, services, properties, null, scope, + // ArtifactFactory.createWireService(), null); + // OutboundWire<?> wire = ArtifactFactory.createOutboundWire("wire", Greeting.class); + // ArtifactFactory.terminateWire(wire); + // + // TargetInvoker invoker = createMock(TargetInvoker.class); + // expect(invoker.isCacheable()).andReturn(false); + // Message response = new MessageImpl(); + // response.setBody("foo"); + // expect(invoker.invoke(eqMessage())).andReturn(response); + // replay(invoker); + // + // for (OutboundInvocationChain chain : wire.getInvocationChains().values()) { + // chain.setTargetInvoker(invoker); + // } + // scope.register(context); + // context.addOutboundWire(wire); + // Greeting greeting = context.getServiceInstance(); + // assertEquals("foo", greeting.greet("foo")); + // verify(invoker); + // + // scope.stop(); + } + + // todo this could be generalized and moved to test module + public static Message eqMessage() { + reportMatcher(new IArgumentMatcher() { + public boolean matches(Object object) { + if (!(object instanceof Message)) { + return false; + } + final Message msg = (Message) object; + Object[] body = (Object[]) msg.getBody(); + return "foo".equals(body[0]); + } + + public void appendTo(StringBuffer stringBuffer) { + } + }); + return null; + } + + /** + * Tests a basic invocation to a target + */ + public void testTargetInvocation() throws Exception { + ModuleScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + Map<String, Object> properties = new Hashtable<String,Object>(); + properties.put("greeting","HeyThere"); + + RubyComponent context = new RubyComponent("source", + implClass2, + null, + services, + properties, + null, + scope, + ArtifactFactory.createWireService(), + null); + scope.register(context); + DataType<String> returnDataType = new DataType<String>(String.class, String.class.getName()); +// Operation<String> operation = new Operation<String>("greet", +// returnDataType, +// null, +// null, +// false, +// null); +// +// TargetInvoker invoker = context.createTargetInvoker(null, +// operation); +// assertEquals("foo", +// invoker.invokeTarget(new String[]{"foo"})); + scope.stop(); + } + + /** + * Tests a basic invocation down a target wire + */ + public void testTargetWireInvocation() throws Exception { + ModuleScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Greeting.class); + Map<String, Object> properties = new Hashtable<String,Object>(); + properties.put("greeting","HeyThere"); + RubyComponent context = new RubyComponent("source", + implClass2, + null, + services, + properties, + null, + scope, + ArtifactFactory.createWireService(), + null); + scope.register(context); + + InboundWire wire = ArtifactFactory.createInboundWire("Greeting", + Greeting.class); + ArtifactFactory.terminateWire(wire); + for (InboundInvocationChain chain : wire.getInvocationChains().values()) { + chain.setTargetInvoker(context.createTargetInvoker(null, + chain.getOperation())); + } + context.addInboundWire(wire); + Greeting greeting = (Greeting) context.getServiceInstance("Greeting"); + assertEquals("foo", + greeting.greet("foo")); + scope.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + implClass1 = new RubyScript("script1", SCRIPT); + implClass2 = new RubyScript("script2", SCRIPT2); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/function/HelloWorldTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/function/HelloWorldTestCase.java new file mode 100644 index 0000000000..c2af5b9b10 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/function/HelloWorldTestCase.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.container.ruby.function; + +import java.net.URL; + +import helloworld.HelloWorldService; + +import org.apache.tuscany.test.SCATestCase; +import org.osoa.sca.CompositeContext; +import org.osoa.sca.CurrentCompositeContext; + +/** + * This shows how to test the HelloWorld service component. + */ +public class HelloWorldTestCase extends SCATestCase { + + private HelloWorldService helloWorldService; + private CompositeContext context = null; + + + protected void setUp() throws Exception { + URL base = getClass().getResource("/META-INF/sca/ruby.system.scdl"); + addExtension("RubyContainer", new URL(base, "default.scdl")); + setApplicationSCDL(getClass().getResource("helloworld.scdl")); + super.setUp(); + + context = CurrentCompositeContext.getContext(); + helloWorldService = context.locateService(HelloWorldService.class, "HelloWorldRubyComponent"); + + //helloWorldService = context.locateService(HelloWorldService.class, "HelloWorldJavaReference"); + } + + public void testHelloWorldWithClass() throws Exception { + assertEquals(helloWorldService.sayHello("petra"), "Hey Howdy from Java Reference petra"); + //System.out.println(helloWorldService.sayHello("petra")); + } + + public void testHelloWorldGlobal() throws Exception { + assertEquals(helloWorldService.sayHello("artep"), "Hey Howdy from Java Reference artep"); + //System.out.println(helloWorldService.sayHello("artep")); + } + + public void testHelloWorldProperty() throws Exception { + HelloWorldService helloWorldService = context.locateService(HelloWorldService.class, "HelloWorldProperty"); + assertEquals(helloWorldService.sayHello("petra"), "Namaskaar petra"); + //System.out.println(helloWorldService.sayHello("petra")); + } + + public void testHelloWorldPropertyDefault() throws Exception { + HelloWorldService helloWorldService = context.locateService(HelloWorldService.class, "HelloWorldPropertyDefault"); + assertEquals(helloWorldService.sayHello("petra"), "Bow Wow petra"); + //System.out.println(helloWorldService.sayHello("petra")); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/mock/Greeting.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/mock/Greeting.java new file mode 100644 index 0000000000..acf71f152b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/java/org/apache/tuscany/container/ruby/mock/Greeting.java @@ -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. + */ +package org.apache.tuscany.container.ruby.mock; + +public interface Greeting { + + String setWire(Greeting ref); + + String greet(String name); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/HelloWorld.componentType b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/HelloWorld.componentType new file mode 100644 index 0000000000..d52b63226c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/HelloWorld.componentType @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="ASCII"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+<componentType xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+ <service name="HelloWorldService">
+ <interface.java interface="helloworld.HelloWorldService"/>
+ </service>
+ <reference name="extHelloWorld">
+ <interface.java interface="helloworld.HelloWorldService"/>
+ </reference>
+ <property name="greeting" type="xsd:string">Hullow</property>
+</componentType>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/HelloWorld.rb b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/HelloWorld.rb new file mode 100644 index 0000000000..3f1a053b15 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/HelloWorld.rb @@ -0,0 +1,33 @@ + # Licensed to the Apache Software Foundation (ASF) under one
+ # or more contributor license agreements. See the NOTICE file
+ # distributed with this work for additional information
+ # regarding copyright ownership. The ASF licenses this file
+ # to you under the Apache License, Version 2.0 (the
+ # "License"); you may not use this file except in compliance
+ # with the License. You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing,
+ # software distributed under the License is distributed on an
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ # KIND, either express or implied. See the License for the
+ # specific language governing permissions and limitations
+ # under the License.
+
+class Helloworld
+
+ def sayHello(s)
+ return "Hello to " + s + " from the Ruby World!"
+ end
+
+end
+
+class HelloWorldServiceRubyImpl
+ attr_writer :extHelloWorld
+ attr_writer :greeting
+
+ def sayHello(s)
+ return @greeting + " " + @extHelloWorld.sayHello(s);
+ end
+end
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/IntrospectableHelloWorld.rb b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/IntrospectableHelloWorld.rb new file mode 100644 index 0000000000..d4edb7a100 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/IntrospectableHelloWorld.rb @@ -0,0 +1,30 @@ + # Licensed to the Apache Software Foundation (ASF) under one
+ # or more contributor license agreements. See the NOTICE file
+ # distributed with this work for additional information
+ # regarding copyright ownership. The ASF licenses this file
+ # to you under the Apache License, Version 2.0 (the
+ # "License"); you may not use this file except in compliance
+ # with the License. You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing,
+ # software distributed under the License is distributed on an
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ # KIND, either express or implied. See the License for the
+ # specific language governing permissions and limitations
+ # under the License.
+
+$SCA = {
+ 'javaInterface' => 'helloworld.HelloWorldService'
+}
+
+def sayHello(s)
+ return "Hello to " + s + " from the Ruby World!"
+end
+
+class HelloWorldServiceRubyImpl
+ def sayHello(s)
+ return "Hello to " + s + " from the Ruby World!"
+ end
+end
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/helloworld.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/helloworld.scdl new file mode 100644 index 0000000000..222beac543 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/helloworld.scdl @@ -0,0 +1,44 @@ +<?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. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:rb="http://incubator.apache.org/tuscany/xmlns/container/rb/1.0-incubator-M2" + + name="HelloWorldComposite"> + + <component name="HelloWorldRubyComponent"> + <rb:implementation.rb script="org/apache/tuscany/container/ruby/function/HelloWorld.rb" class="HelloWorldServiceRubyImpl"/> + <reference name="extHelloWorld" target="HelloWorldJavaReference">HelloWorldJavaReference</reference> + <property name="greeting">Hey</property> + </component> + + <component name="HelloWorldJavaReference"> + <implementation.java class="helloworld.HelloWorldServiceImpl"/> + <property name="greeting">Howdy</property> + </component> + + <component name="HelloWorldProperty"> + <rb:implementation.rb script="org/apache/tuscany/container/ruby/function/propertyTest.rb" class="HelloWorldPropertyTest"/> + <property name="GREETING">Namaskaar</property> + </component> + + <component name="HelloWorldPropertyDefault"> + <rb:implementation.rb script="org/apache/tuscany/container/ruby/function/propertyTest.rb" class="HelloWorldPropertyTest"/> + </component> +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/propertyTest.componentType b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/propertyTest.componentType new file mode 100644 index 0000000000..6b37990b8b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/propertyTest.componentType @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="ASCII"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+
+<componentType xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+ <service name="HelloWorldService">
+ <interface.java interface="helloworld.HelloWorldService"/>
+ </service>
+ <property name="GREETING" type="xsd:string">Bow Wow</property>
+</componentType>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/propertyTest.rb b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/propertyTest.rb new file mode 100644 index 0000000000..7aa0f3e8ea --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/function/propertyTest.rb @@ -0,0 +1,24 @@ + # Licensed to the Apache Software Foundation (ASF) under one
+ # or more contributor license agreements. See the NOTICE file
+ # distributed with this work for additional information
+ # regarding copyright ownership. The ASF licenses this file
+ # to you under the Apache License, Version 2.0 (the
+ # "License"); you may not use this file except in compliance
+ # with the License. You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing,
+ # software distributed under the License is distributed on an
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ # KIND, either express or implied. See the License for the
+ # specific language governing permissions and limitations
+ # under the License.
+
+class HelloWorldPropertyTest
+ attr_writer :GREETING
+
+ def sayHello(s)
+ return @GREETING + " " + s;
+ end
+end
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/jruby/helloworld.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/jruby/helloworld.wsdl new file mode 100644 index 0000000000..67067f044a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/jruby/helloworld.wsdl @@ -0,0 +1,78 @@ +<?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. + --> +<wsdl:definitions targetNamespace="http://helloworld" xmlns:tns="http://helloworld" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" + name="helloworld"> + + <wsdl:types> + <schema elementFormDefault="qualified" targetNamespace="http://helloworld" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/2001/XMLSchema"> + + <element name="getGreetings"> + <complexType> + <sequence> + <element name="name" type="xsd:string"/> + </sequence> + </complexType> + </element> + + <element name="getGreetingsResponse"> + <complexType> + <sequence> + <element name="getGreetingsReturn" type="xsd:string"/> + </sequence> + </complexType> + </element> + </schema> + </wsdl:types> + + <wsdl:message name="getGreetingsRequest"> + <wsdl:part element="tns:getGreetings" name="parameters"/> + </wsdl:message> + + <wsdl:message name="getGreetingsResponse"> + <wsdl:part element="tns:getGreetingsResponse" name="parameters"/> + </wsdl:message> + + <wsdl:portType name="HelloWorld"> + <wsdl:operation name="getGreetings"> + <wsdl:input message="tns:getGreetingsRequest" name="getGreetingsRequest"/> + <wsdl:output message="tns:getGreetingsResponse" name="getGreetingsResponse"/> + </wsdl:operation> + </wsdl:portType> + + <wsdl:binding name="HelloWorldSoapBinding" type="tns:HelloWorld"> + <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + <wsdl:operation name="getGreetings"> + <wsdlsoap:operation soapAction=""/> + <wsdl:input name="getGreetingsRequest"> + <wsdlsoap:body use="literal"/> + </wsdl:input> + <wsdl:output name="getGreetingsResponse"> + <wsdlsoap:body use="literal"/> + </wsdl:output> + </wsdl:operation> + </wsdl:binding> + + <wsdl:service name="HelloWorldService"> + <wsdl:port binding="tns:HelloWorldSoapBinding" name="HelloWorldSoapPort"> + <wsdlsoap:address location="http://localhost:8080/sample-helloworldws/services/HelloWorldWebService"/> + </wsdl:port> + </wsdl:service> + +</wsdl:definitions> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/mock/test.rb b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/mock/test.rb new file mode 100644 index 0000000000..ef2694b475 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.ruby/src/test/resources/org/apache/tuscany/container/ruby/mock/test.rb @@ -0,0 +1 @@ +//Test Script
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/.ruleset new file mode 100644 index 0000000000..3886f07f2d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/.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-M2/sca/services/containers/container.spring/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/LICENSE.txt new file mode 100755 index 0000000000..0084319535 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, serviceDefinition 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-M2/sca/services/containers/container.spring/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/README.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/README.txt new file mode 100755 index 0000000000..9b26d1690a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/README.txt @@ -0,0 +1,35 @@ +Apache Tuscany M1 build (May, 2006) +=================================== + +http://incubator.apache.org/tuscany/ + +Tuscany is an effort undergoing incubation at the Apache Software Foundation +(ASF), sponsored by the 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. + + +Support +------- + +Any problem with this release can be reported to the Tuscany mailing list +or in the JIRA issue tracker. + +Mailing list subscription: + tuscany-dev-subscribe@ws.apache.org + +Jira: + http://issues.apache.org/jira/browse/Tuscany + + +Thank you for using Tuscany! + + +The Tuscany Team. + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/pom.xml new file mode 100755 index 0000000000..057f5b7d61 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/pom.xml @@ -0,0 +1,81 @@ +<?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> + + <parent> + <groupId>org.apache.tuscany.sca.services.containers</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>spring</artifactId> + <name>Apache Tuscany Spring Framework Container</name> + <description>Container for managing Spring composites</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca.runtime</groupId> + <artifactId>webapp</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring</artifactId> + <version>2.0</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <version>1.0.4</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>test</artifactId> + <version>${sca.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymockclassextension</artifactId> + </dependency> + + + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + </dependency> + + </dependencies> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/config/SCANamespaceHandlerResolver.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/config/SCANamespaceHandlerResolver.java new file mode 100644 index 0000000000..047d2b4ad1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/config/SCANamespaceHandlerResolver.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.container.spring.config; + +import org.apache.tuscany.spi.model.CompositeComponentType; + +import org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver; +import org.springframework.beans.factory.xml.NamespaceHandler; +import org.springframework.sca.config.ScaNamespaceHandler; + +/** + * Overrides the default Spring namespace resolver to automatically register {@link SCANamespaceHandler} instead of + * requiring a value to be supplied in a Spring configuration + * <p/> + * TODO: Figure out how to activate this impl + * + * @version $$Rev$$ $$Date$$ + */ +public class SCANamespaceHandlerResolver extends DefaultNamespaceHandlerResolver { + + private static final String SCA_NAMESPACE = "http://www.springframework.org/schema/sca"; + + private ScaNamespaceHandler handler; + + public SCANamespaceHandlerResolver(ClassLoader classLoader, CompositeComponentType componentType) { + super(classLoader); + handler = new ScaNamespaceHandler(/*componentType*/); + } + + public SCANamespaceHandlerResolver(String handlerMappingsLocation, + ClassLoader classLoader, + CompositeComponentType componentType) { + super(classLoader, handlerMappingsLocation); + handler = new ScaNamespaceHandler(/*componentType*/); + } + + public NamespaceHandler resolve(String namespaceUri) { + if (SCA_NAMESPACE.equals(namespaceUri)) { + return handler; + } + return super.resolve(namespaceUri); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/config/ScaApplicationContext.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/config/ScaApplicationContext.java new file mode 100644 index 0000000000..cdf33b0ea1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/config/ScaApplicationContext.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.container.spring.config; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.AbstractXmlApplicationContext; +import org.springframework.core.io.Resource; +import org.springframework.sca.ScaAdapterAware; +import org.springframework.sca.ScaAdapterPostProcessor; + +import org.apache.tuscany.container.spring.impl.SpringScaAdapter; +import org.apache.tuscany.container.spring.model.SpringComponentType; + +/** + * @author Andy Piper + * @since 2.1 + */ +public class ScaApplicationContext extends AbstractXmlApplicationContext { + public static final String APP_CONTEXT_PROP = "org.springframework.sca.application.context"; + private Resource appXml; + private SpringComponentType componentType; + + public ScaApplicationContext(Resource appXml, SpringComponentType componentType) { + this(null, appXml, componentType); + } + + public ScaApplicationContext(ApplicationContext parent, Resource appXml, SpringComponentType componentType) { + super(parent); + this.appXml = appXml; + this.componentType = componentType; + refresh(); + } + + protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) { + // beanDefinitionReader.setEntityResolver(null); + beanDefinitionReader + .setNamespaceHandlerResolver(new SCANamespaceHandlerResolver(getClassLoader(), componentType)); + } + + protected Resource[] getConfigResources() { + return new Resource[]{appXml}; + } + + protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + super.postProcessBeanFactory(beanFactory); + beanFactory.addBeanPostProcessor(new ScaAdapterPostProcessor(new SpringScaAdapter(componentType))); + beanFactory.ignoreDependencyInterface(ScaAdapterAware.class); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringComponentTypeLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringComponentTypeLoader.java new file mode 100644 index 0000000000..fa815eee78 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringComponentTypeLoader.java @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.spring.impl; + +import org.springframework.context.support.AbstractRefreshableApplicationContext; +import org.springframework.core.io.Resource; +import org.springframework.sca.ScaServiceExporter; + +import org.apache.tuscany.container.spring.config.ScaApplicationContext; +import org.apache.tuscany.container.spring.model.SpringComponentType; +import org.apache.tuscany.container.spring.model.SpringImplementation; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentTypeLoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.host.RuntimeInfo; + +/** + * Loads a component type for a Spring <code>ApplicationContext</code>. The implementation creates a new instance of a + * Spring application context which is configured with SCA namespace handlers for generating component type information + * + * @version $$Rev$$ $$Date$$ + */ + +public class SpringComponentTypeLoader extends ComponentTypeLoaderExtension<SpringImplementation> { + public static final String SERVICE_BEAN_SUFFIX = ".SCAService"; + + private org.apache.tuscany.host.RuntimeInfo runtimeInfo; + + public SpringComponentTypeLoader(@Autowire LoaderRegistry loaderRegistry, @Autowire RuntimeInfo runtimeInfo) { + super(loaderRegistry); + this.runtimeInfo = runtimeInfo; + } + + @Override + protected Class<SpringImplementation> getImplementationClass() { + return SpringImplementation.class; + } + + /** + * Responsible for loading the Spring composite component type. The the application context is instantiated here as + * it is needed to derive component type information. Since the component type is loaded per SCDL entry (i.e. + * composite use) one application context instance will be created per Spring composite instance. + */ + @SuppressWarnings("unchecked") + public void load(CompositeComponent parent, + SpringImplementation implementation, + DeploymentContext deploymentContext) throws LoaderException { + if (implementation.getComponentType() != null) { + // FIXME hack since the builder registry loads the implementation type and the Spring implementation loader + // needs to as well. The second call is done by the builder registry and we just ignore it. + return; + } + Resource resource = implementation.getApplicationResource(); + SpringComponentType componentType = new SpringComponentType(); + // REVIEW andyp -- pass in deploymentContext.getClassLoader()? + AbstractRefreshableApplicationContext ctx; + if (runtimeInfo instanceof SpringRuntimeInfo) { + ctx = ((SpringRuntimeInfo) runtimeInfo).getApplicationContext(); + } else { + ctx = new ScaApplicationContext(resource, componentType); + } + componentType.setApplicationContext(ctx); // FIXME andyp@bea.com -- don't do this! + + // If there are <sca:service> elements, they define (and limit) the services exposed + // in the componentType. + String [] serviceBeanNames = ctx.getBeanNamesForType(ScaServiceExporter.class); + for (String serviceBeanName : serviceBeanNames) { + int nSuffix = serviceBeanName.indexOf(SERVICE_BEAN_SUFFIX); + if (nSuffix == -1) { + continue; + } + + String serviceName = serviceBeanName.substring(0, nSuffix); + ScaServiceExporter serviceBean = (ScaServiceExporter) ctx.getBean(serviceName); + // REVIEW andyp -- use the class directly? + String serviceTypeName = serviceBean.getServiceType().getName(); + try { + Class serviceInterface = Class.forName(serviceTypeName, true, deploymentContext.getClassLoader()); + componentType.addServiceType(serviceName, serviceInterface); + //ServiceDefinition service = createService(serviceInterface); + //componentType.getServices().put(serviceName, service); + } catch (ClassNotFoundException e) { + throw new LoaderException(e); + } + } + // if no service tags are specified, expose all beans + componentType.setExposeAllBeans(componentType.getServiceTypes().isEmpty()); + implementation.setComponentType(componentType); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringCompositeBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringCompositeBuilder.java new file mode 100644 index 0000000000..6ec5d8fdd7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringCompositeBuilder.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.spring.impl; + +import org.apache.tuscany.spi.QualifiedName; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentBuilderExtension; +import org.apache.tuscany.spi.model.Binding; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.CompositeComponentType; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; + +import org.apache.tuscany.container.spring.model.SpringImplementation; +import org.springframework.context.support.AbstractApplicationContext; + +/** + * Creates a {@link org.apache.tuscany.container.spring.impl.SpringCompositeComponent} from an assembly model + * + * @version $$Rev$$ $$Date$$ + */ +public class SpringCompositeBuilder extends ComponentBuilderExtension<SpringImplementation> { + + public Component build(CompositeComponent parent, + ComponentDefinition<SpringImplementation> componentDefinition, + DeploymentContext deploymentContext) throws BuilderConfigException { + String name = componentDefinition.getName(); + SpringImplementation implementation = componentDefinition.getImplementation(); + AbstractApplicationContext applicationContext = implementation.getComponentType().getApplicationContext(); + SpringCompositeComponent component = + new SpringCompositeComponent(name, applicationContext, parent, connector, null); + CompositeComponentType<BoundServiceDefinition<? extends Binding>, + BoundReferenceDefinition<? extends Binding>, + ? extends Property> componentType = implementation.getComponentType(); + + // We still need to set the target invoker as opposed to having the connector do it since the + // Spring context is "opaque" to the wiring fabric. In other words, the Spring context does not expose + // its beans as SCA components to the connector to wire the services to + for (BoundServiceDefinition<? extends Binding> serviceDefinition : componentType.getServices().values()) { + // call back into builder registry to handle building of services + Service service = (Service) builderRegistry.build(parent, serviceDefinition, deploymentContext); + // wire serviceDefinition to bean invokers + InboundWire wire = service.getInboundWire(); + QualifiedName targetName = new QualifiedName(serviceDefinition.getTarget().getPath()); + for (InboundInvocationChain chain : wire.getInvocationChains().values()) { + // FIXME this should go to the connector and get policy and be invoked from SpringComposite.prepare() + chain.addInterceptor(new SpringInterceptor()); + chain.setTargetInvoker(component.createTargetInvoker(targetName.getPartName(), chain.getOperation())); + } + component.register(service); + } + for (BoundReferenceDefinition<?> referenceDefinition : componentType.getReferences().values()) { + // call back into builder registry to handle building of references + Reference reference = (Reference) builderRegistry.build(parent, referenceDefinition, deploymentContext); + connector.connect(reference); + component.register(reference); + } + return component; + } + + protected Class<SpringImplementation> getImplementationType() { + return SpringImplementation.class; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringCompositeComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringCompositeComponent.java new file mode 100644 index 0000000000..b30202cb96 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringCompositeComponent.java @@ -0,0 +1,252 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.spring.impl; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.Locale; +import java.util.Map; + +import org.w3c.dom.Document; + +import org.apache.tuscany.spi.builder.Connector; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.extension.CompositeComponentExtension; +import static org.apache.tuscany.spi.idl.java.JavaIDLUtils.findMethod; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.MessageSourceResolvable; +import org.springframework.context.NoSuchMessageException; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.core.io.Resource; + +/** + * A composite implementation responsible for managing Spring application contexts. + * + * @version $$Rev$$ $$Date$$ + */ +public class SpringCompositeComponent extends CompositeComponentExtension { + private static final String[] EMPTY_ARRAY = new String[0]; + private AbstractApplicationContext springContext; + + /** + * Creates a new composite + * + * @param name the name of the SCA composite + * @param springContext the pre-instantiated Spring applicaiton context + * @param parent the SCA composite parent + * @param connector the connector to use for wiring children + * @param propertyValues the values of this composite's Properties + */ + public SpringCompositeComponent(String name, + AbstractApplicationContext springContext, + CompositeComponent parent, + Connector connector, + Map<String, Document> propertyValues) { + super(name, parent, connector, propertyValues); + SCAApplicationContext scaApplicationContext = new SCAApplicationContext(); + springContext.setParent(scaApplicationContext); + // REVIEW we need to refresh to pick up the parent but this is not optimal + springContext.refresh(); + this.springContext = springContext; + } + + public TargetInvoker createTargetInvoker(String targetName, Operation operation) { + ServiceContract contract = operation.getServiceContract(); + Method[] methods = contract.getInterfaceClass().getMethods(); + Method method = findMethod(operation, methods); + // FIXME test m == null + // Treat the serviceName as the Spring bean name to look up + return new SpringInvoker(targetName, method, springContext); + } + + public void setScopeContainer(ScopeContainer scopeContainer) { + // not needed + } + + public ConfigurableApplicationContext getApplicationContext() { + return springContext; + } + + public void prepare() { + // TODO handle only references with a composite binding + } + + public void start() { + super.start(); + for (SCAObject child : children.values()) { + child.start(); + } + springContext.start(); + } + + public void stop() { + super.stop(); + springContext.stop(); + } + + public <T> T locateService(Class<T> serviceInterface, String name) { + return serviceInterface.cast(springContext.getBean(name)); + } + + /** + * An inner class is required to act as the Spring application context parent as opposed to implementing the + * interface since the return types for {@link org.springframework.context.ApplicationContext#getParent()} and + * {@link org.apache.tuscany.spi.component.CompositeComponent#getParent()} clash + */ + private class SCAApplicationContext implements ApplicationContext { + + public Object getBean(String name) throws BeansException { + return getBean(name, null); + } + + public Object getBean(String name, Class requiredType) throws BeansException { + SCAObject object = children.get(name); // keep cast due to compiler error + if (object == null) { + return null; + } + Class<?> type; + if (object instanceof Reference) { + type = ((Reference) object).getInterface(); + } else if (object instanceof Service) { + type = ((Service) object).getInterface(); + } else { + throw new AssertionError("Illegal object type [" + name + "]"); + } + if (requiredType != null && requiredType.isAssignableFrom(type)) { + // need null check since Spring may pass in a null + throw new BeanNotOfRequiredTypeException(name, requiredType, type); + } + return object.getServiceInstance(); + } + + public boolean containsBean(String name) { + return children.get(name) != null; + } + + public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return children.get(name) != null; + } + + public Class getType(String name) throws NoSuchBeanDefinitionException { + return null; + } + + public String[] getAliases(String name) throws NoSuchBeanDefinitionException { + return EMPTY_ARRAY; + } + + public ApplicationContext getParent() { + return null; + } + + public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException { + return null; + } + + public String getDisplayName() { + return getName(); + } + + public long getStartupDate() { + return 0; + } + + public boolean containsBeanDefinition(String beanName) { + return false; + } + + public int getBeanDefinitionCount() { + return 0; + } + + public String[] getBeanDefinitionNames() { + return new String[0]; + } + + public String[] getBeanNamesForType(Class type) { + return new String[0]; + } + + public String[] getBeanNamesForType(Class type, boolean includePrototypes, boolean includeFactoryBeans) { + return new String[0]; + } + + public Map getBeansOfType(Class type) throws BeansException { + return null; + } + + public Map getBeansOfType(Class type, boolean includePrototypes, boolean includeFactoryBeans) + throws BeansException { + return null; + } + + public BeanFactory getParentBeanFactory() { + return null; + } + + public boolean containsLocalBean(String name) { + return false; + } + + public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { + return null; + } + + public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException { + return null; + } + + public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { + return null; + } + + public void publishEvent(ApplicationEvent event) { + + } + + public Resource[] getResources(String locationPattern) throws IOException { + return new Resource[0]; + } + + public Resource getResource(String location) { + return null; + } + + public ClassLoader getClassLoader() { + // REVIEW: this is almost certainly flawed, but it's not clear how the SCA runtime's + // resource loading mechanism is exposed right now. + return this.getClass().getClassLoader(); + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringImplementationLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringImplementationLoader.java new file mode 100644 index 0000000000..c95375cad2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringImplementationLoader.java @@ -0,0 +1,196 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.spring.impl; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import javax.xml.namespace.QName; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; + +import org.apache.tuscany.container.spring.model.SpringComponentType; +import org.apache.tuscany.container.spring.model.SpringImplementation; +import org.apache.tuscany.host.RuntimeInfo; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; + +/** + * Loader for handling Spring <spring:implementation.spring> elements. + */ +public class SpringImplementationLoader extends LoaderExtension<SpringImplementation> { + private static final QName IMPLEMENTATION_SPRING = new QName("http://www.osoa.org/xmlns/sca/1.0", + "implementation.spring"); + + private static final String APPLICATION_CONTEXT = "application-context.xml"; + + private static final QName SERVICE_ELEMENT = new QName(XML_NAMESPACE_1_0, "service"); + private static final QName REFERENCE_ELEMENT = new QName(XML_NAMESPACE_1_0, "reference"); + + private final RuntimeInfo runtimeInfo; + + public SpringImplementationLoader(@Autowire LoaderRegistry registry, @Autowire RuntimeInfo runtimeInfo) { + super(registry); + this.runtimeInfo = runtimeInfo; + } + + public QName getXMLType() { + return IMPLEMENTATION_SPRING; + } + + @SuppressWarnings("unchecked") + public SpringImplementation load(CompositeComponent parent, + XMLStreamReader reader, + DeploymentContext deploymentContext) + throws XMLStreamException, LoaderException { + + String locationAttr = reader.getAttributeValue(null, "location"); + if (locationAttr == null && !contextProvided()) { + throw new MissingResourceException("No location supplied"); + } + + SpringImplementation implementation = new SpringImplementation(); + ClassLoader classLoader = deploymentContext.getClassLoader(); + if (!contextProvided()) { + implementation.setApplicationResource(getApplicationContextResource(locationAttr, classLoader)); + } + registry.loadComponentType(parent, implementation, deploymentContext); + SpringComponentType type = implementation.getComponentType(); + while (true) { + switch (reader.next()) { + case START_ELEMENT: + QName qname = reader.getName(); + if (SERVICE_ELEMENT.equals(qname)) { + BoundServiceDefinition service = + (BoundServiceDefinition) registry.load(parent, reader, deploymentContext); + if (!type.isExposeAllBeans()) { + String name = service.getName(); + if (!type.getServiceTypes().containsKey(name)) { + LoaderException e = new LoaderException("No service defined in Spring context for "); + e.setIdentifier(name); + throw e; + } + } + type.getDeclaredServices().put(service.getName(), service); + } else if (REFERENCE_ELEMENT.equals(qname)) { + BoundReferenceDefinition reference = + (BoundReferenceDefinition) registry.load(parent, reader, deploymentContext); + type.getDeclaredReferences().put(reference.getName(), reference); + } + break; + case END_ELEMENT: + if (IMPLEMENTATION_SPRING.equals(reader.getName())) { + return implementation; + } + } + } + } + + protected Resource getApplicationContextResource(String locationAttr, ClassLoader cl) throws LoaderException { + assert runtimeInfo != null; + File manifestFile = null; + File appXmlFile; + File locationFile = new File(locationAttr); + + if (!locationFile.isAbsolute()) { + locationFile = new File(runtimeInfo.getApplicationRootDirectory(), locationAttr); + } + if (!locationFile.exists()) { + // FIXME hack + URL url = cl.getResource(locationAttr); + if (url != null) { + return new UrlResource(url); + } + throw new MissingResourceException(locationFile.toString()); + } + + if (locationFile.isDirectory()) { + try { + manifestFile = new File(locationFile, "META-INF/MANIFEST.MF"); + if (manifestFile.exists()) { + Manifest mf = new Manifest(new FileInputStream(manifestFile)); + Attributes mainAttrs = mf.getMainAttributes(); + String appCtxPath = mainAttrs.getValue("Spring-Context"); + if (appCtxPath != null) { + appXmlFile = new File(locationFile, appCtxPath); + if (appXmlFile.exists()) { + return new UrlResource(appXmlFile.toURL()); + } + } + } + // no manifest-specified Spring context, use default + appXmlFile = new File(locationFile, APPLICATION_CONTEXT); + if (appXmlFile.exists()) { + return new UrlResource(appXmlFile.toURL()); + } + } catch (IOException e) { + throw new LoaderException("Error reading manifest " + manifestFile); + } + } else { + try { + JarFile jf = new JarFile(locationFile); + JarEntry je; + Manifest mf = jf.getManifest(); + if (mf != null) { + Attributes mainAttrs = mf.getMainAttributes(); + String appCtxPath = mainAttrs.getValue("Spring-Context"); + if (appCtxPath != null) { + je = jf.getJarEntry(appCtxPath); + if (je != null) { + // TODO return a Spring specific Resouce type for jars + return new UrlResource(new URL("jar:" + locationFile.toURL() + "!/" + appCtxPath)); + } + } + } + je = jf.getJarEntry(APPLICATION_CONTEXT); + if (je != null) { + return new UrlResource(new URL("jar:" + locationFile.toURI().toURL() + "!" + APPLICATION_CONTEXT)); + } + } catch (IOException e) { + // bad archive + // TODO: create a more appropriate exception type + throw new MissingResourceException(locationAttr, e); + } + } + throw new MissingResourceException(APPLICATION_CONTEXT); + } + + private boolean contextProvided() { + return runtimeInfo instanceof SpringRuntimeInfo; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringInterceptor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringInterceptor.java new file mode 100644 index 0000000000..fb7f0bd99c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringInterceptor.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.container.spring.impl; + +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; + +/** + * A temporary interceptor until the connector is updated + * + * @version $Rev$ $Date$ + */ +public class SpringInterceptor implements Interceptor { + + public Message invoke(Message msg) throws InvocationRuntimeException { + TargetInvoker invoker = msg.getTargetInvoker(); + if (invoker == null) { + throw new InvocationRuntimeException("No target invoker specified on message"); + } + return invoker.invoke(msg); + } + + public void setNext(Interceptor next) { + throw new IllegalStateException("This interceptor must be the last one in an target interceptor chain"); + } + + public Interceptor getNext() { + return null; + } + + public boolean isOptimizable() { + return true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringInvoker.java new file mode 100644 index 0000000000..6e05c888ae --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringInvoker.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.spring.impl; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.component.TargetException; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; + +/** + * Dispatches to an operation on a Spring bean. Since Spring manages bean lifecycle and scope through resolution in the + * target proxy, the invoker can safely cache the target proxy. + * + * @version $$Rev$$ $$Date$$ + */ +public class SpringInvoker implements TargetInvoker { + private ApplicationContext springContext; + // default to true since Spring handles resolution + private boolean cacheable = true; + private String beanName; + private Method method; + // caching is thread-safe since Spring handles resolution + private Object bean; + + public SpringInvoker(String beanName, Method method, ApplicationContext context) { + this.beanName = beanName; + this.method = method; + springContext = context; + } + + public Object invokeTarget(final Object object) throws InvocationTargetException { + if (bean == null) { + try { + bean = springContext.getBean(beanName); + } catch (BeansException e) { + throw new TargetException(e); + } + } + try { + if (object != null && !object.getClass().isArray()) { + return method.invoke(bean, object); + } else { + return method.invoke(bean, (Object[]) object); + } + } catch (IllegalAccessException e) { + throw new InvocationTargetException(e); + } + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (InvocationTargetException e) { + msg.setBodyWithFault(e.getCause()); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } + + public boolean isCacheable() { + return cacheable; + } + + public void setCacheable(boolean cacheable) { + this.cacheable = cacheable; + } + + public boolean isOptimizable() { + return false; + } + + + public SpringInvoker clone() throws CloneNotSupportedException { + SpringInvoker invoker = (SpringInvoker) super.clone(); + invoker.bean = null; + return invoker; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringRuntimeInfo.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringRuntimeInfo.java new file mode 100644 index 0000000000..8b4f0ac905 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringRuntimeInfo.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.container.spring.impl; + +import java.io.File; +import java.net.URL; + +import org.apache.tuscany.host.RuntimeInfo; +import org.springframework.context.support.AbstractRefreshableApplicationContext; + +/** + * @author Andy Piper + * @since 2.1 + */ +public class SpringRuntimeInfo implements RuntimeInfo { + private AbstractRefreshableApplicationContext applicationContext; + private File appRootDir; + + public SpringRuntimeInfo(File appRootDir, AbstractRefreshableApplicationContext applicationContext) { + this.appRootDir = appRootDir; + this.applicationContext = applicationContext; + } + + public AbstractRefreshableApplicationContext getApplicationContext() { + return applicationContext; + } + + public void setApplicationContext(AbstractRefreshableApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + public File getInstallDirectory() { + return null; + } + + public File getApplicationRootDirectory() { + return appRootDir; + } + + public URL getBaseURL() { + return null; + } + + public boolean isOnline() { + return true; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringScaAdapter.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringScaAdapter.java new file mode 100644 index 0000000000..ca645db823 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/impl/SpringScaAdapter.java @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tuscany.container.spring.impl; + +import org.apache.tuscany.container.spring.model.SpringComponentType; +import org.springframework.sca.ScaAdapter; + +/** + * @author Andy Piper + * @since 2.1 + */ +public class SpringScaAdapter implements ScaAdapter { + //private final SpringComponentType componentType; + + public SpringScaAdapter(SpringComponentType componentType) { + //this.componentType = componentType; + } + + public Object getServiceReference(String referenceName, Class referenceType, String moduleName, + String defaultServiceName) { + /* + ReferenceDefinition reference = null; + componentType.getReferences().put(referenceName, reference); + */ + return null; + } + + public Object getPropertyReference(String propertyName, Class propertyType, String moduleName) { + return null; + } + + public void publishAsService(Object serviceImplementation, Class serviceInterface, String serviceName, + String moduleName) { + /* + componentType.addServiceType(serviceName, serviceInterface); + ServiceDefinition service = null; + componentType.getServices().put(serviceName, service); + */ + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringComponentType.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringComponentType.java new file mode 100644 index 0000000000..d8758ffdb7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringComponentType.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.spring.model; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.model.CompositeComponentType; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import org.springframework.context.support.AbstractApplicationContext; + +/** + * Component type information for a Spring composite component implementation type. A component type is associated with + * a Spring application context + * + * @version $Rev$ $Date$ + */ +public class SpringComponentType<S extends ServiceDefinition, + R extends ReferenceDefinition, + P extends Property<?>> extends CompositeComponentType<S, R, P> { + + private AbstractApplicationContext applicationContext; + private Map<String, Class<?>> serviceTypes = new HashMap<String, Class<?>>(); + private boolean exposeAllBeans; + + public SpringComponentType(AbstractApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + public SpringComponentType() { + } + + // FIXME andyp@bea.com -- this is a component type it should NOT contain bean instances! + + /** + * Returns the application context for the component type + */ + public AbstractApplicationContext getApplicationContext() { + return applicationContext; + } + + public void setApplicationContext(AbstractApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + /** + * Returns a collection of service types defined by <code>sca:service</code> elements in a Spring configuration. + * Service types define beans that can be targets of services defined in the SCDL Spring composite declaration. For + * each service type, there must be a corresponding service definition as part of the Spring composite declaration + * per the SCA specification. + */ + public Map<String, Class<?>> getServiceTypes() { + return serviceTypes; + } + + /** + * Adds a service type to the component declaration defined by <code>sca:service</code> elements in a Spring + * configuration. + * + * @param name the name of the service + * @param type the interface type of the target bean + */ + public void addServiceType(String name, Class<?> type) { + this.serviceTypes.put(name, type); + } + + /** + * Returns true if all beans in the Spring application context may be service targets or false if service types are + * defined + */ + public boolean isExposeAllBeans() { + return exposeAllBeans; + } + + /** + * Sets if all beans in the Spring application context may be service targets or false if service types are defined + */ + public void setExposeAllBeans(boolean exposeAllBeans) { + this.exposeAllBeans = exposeAllBeans; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringImplementation.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringImplementation.java new file mode 100644 index 0000000000..7780894f56 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringImplementation.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.spring.model; + +import org.apache.tuscany.spi.model.Binding; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.apache.tuscany.spi.model.Implementation; +import org.apache.tuscany.spi.model.Property; + +import org.springframework.core.io.Resource; + +/** + * Represents a composite whose implementation type is a Spring application context. + * + * @version $$Rev$$ $$Date$$ + */ +public class SpringImplementation extends Implementation<SpringComponentType<BoundServiceDefinition<? extends Binding>, + BoundReferenceDefinition<? extends Binding>, ? extends Property>> { + + private String location; + private Resource applicationResource; + + public SpringImplementation() { + } + + public SpringImplementation(SpringComponentType< + BoundServiceDefinition<? extends Binding>, + BoundReferenceDefinition<? extends Binding>, + ? extends Property> componentType) { + super(componentType); + } + + /** + * Returns the path of the Spring application context configuration + */ + public String getLocation() { + return location; + } + + /** + * Sets the path of the Spring application context configuration + */ + public void setLocation(String location) { + this.location = location; + } + + /** + * Returns the Spring configuration resource for the application context + */ + public Resource getApplicationResource() { + return applicationResource; + } + + /** + * Sets the Spring configuration resource for the application context + */ + public void setApplicationResource(Resource applicationXml) { + this.applicationResource = applicationXml; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringServiceContract.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringServiceContract.java new file mode 100644 index 0000000000..3a88991e4b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/model/SpringServiceContract.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.spring.model; + +import org.apache.tuscany.spi.model.ServiceContract; + +/** + * @version $Rev$ $Date$ + */ +public class SpringServiceContract extends ServiceContract { + + public SpringServiceContract(String interfaceName) { + super(interfaceName); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/webapp/ScaWebApplicationContext.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/webapp/ScaWebApplicationContext.java new file mode 100644 index 0000000000..2284d32201 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/webapp/ScaWebApplicationContext.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.container.spring.webapp; + +import java.io.File; +import java.net.URL; + +import javax.servlet.ServletContext; + +import org.apache.tuscany.api.TuscanyRuntimeException; +import org.apache.tuscany.container.spring.config.SCANamespaceHandlerResolver; +import org.apache.tuscany.container.spring.impl.SpringScaAdapter; +import org.apache.tuscany.container.spring.model.SpringComponentType; +import org.apache.tuscany.runtime.webapp.WebappRuntime; +import org.apache.tuscany.runtime.webapp.WebappUtil; +import org.apache.tuscany.runtime.webapp.WebappUtilImpl; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.core.io.Resource; +import org.springframework.sca.ScaAdapterAware; +import org.springframework.sca.ScaAdapterPostProcessor; +import org.springframework.util.Assert; +import org.springframework.web.context.ConfigurableWebApplicationContext; +import org.springframework.web.context.support.XmlWebApplicationContext; + +/** + * WebApplicationContext implementation that understands SCA extensions. + * This class is not very complicated, the key issue is getting hold of a reference + * to the Tuscany runtime which the webapp is using. + * + * @author Andy Piper + */ +public class ScaWebApplicationContext extends XmlWebApplicationContext + implements ConfigurableWebApplicationContext { + private WebappRuntime runtime; + private SpringComponentType componentType; + + public ScaWebApplicationContext() { + } + + protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) { +// beanDefinitionReader.setEntityResolver(null); + beanDefinitionReader + .setNamespaceHandlerResolver(new SCANamespaceHandlerResolver(getClassLoader(), componentType)); + } + + public Resource getResource(String location) { + Assert.notNull(location, "location is required"); + return super.getResource(location); + } + + /* (non-Javadoc) + * @see org.springframework.context.support.AbstractApplicationContext#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) + */ + protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + super.postProcessBeanFactory(beanFactory); + beanFactory.addBeanPostProcessor(new ScaAdapterPostProcessor + (new SpringScaAdapter(componentType))); + beanFactory.ignoreDependencyInterface(ScaAdapterAware.class); + } + + protected void onRefresh() { + if (runtime != null) { // egregious hack to prevent recursion in refresh() + return; + } + ServletContext servletContext = getServletContext(); + WebappUtil utils = getUtils(servletContext); + + try { + ClassLoader webappClassLoader = Thread.currentThread().getContextClassLoader(); + ClassLoader bootClassLoader = utils.getBootClassLoader(webappClassLoader); + runtime = utils.getRuntime(bootClassLoader); + URL systemScdl = utils.getSystemScdl(bootClassLoader); + URL applicationScdl = utils.getApplicationScdl(webappClassLoader); + + runtime.setMonitorFactory(runtime.createDefaultMonitorFactory()); + runtime.setApplicationName(utils.getApplicationName()); + runtime.setServletContext(servletContext); + runtime.setHostClassLoader(webappClassLoader); + runtime.setSystemScdl(systemScdl); + runtime.setApplicationScdl(applicationScdl); + runtime.setRuntimeInfo(new SpringWebappRuntimeInfo(getApplicationRootDirectory(), this)); + runtime.initialize(); + } catch (TuscanyRuntimeException e) { + servletContext.log(e.getMessage(), e); + throw e; + } + } + + protected WebappUtil getUtils(ServletContext servletContext) { + return new WebappUtilImpl(servletContext); + } + + protected void onClose() { + if (runtime != null) { + runtime.destroy(); + runtime = null; + } + } + + /** + * What does this do and why to we need it? + * @return + */ + private File getApplicationRootDirectory() { + String property = System.getProperty("tuscany.applicationRootDir"); + if (property != null) { + return new File(property); + } + + return new File(System.getProperty("user.dir")); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/webapp/SpringWebappRuntimeInfo.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/webapp/SpringWebappRuntimeInfo.java new file mode 100644 index 0000000000..a860049462 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/apache/tuscany/container/spring/webapp/SpringWebappRuntimeInfo.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.spring.webapp; + +import java.io.File; +import javax.servlet.ServletContext; + +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.XmlWebApplicationContext; + +import org.apache.tuscany.container.spring.impl.SpringRuntimeInfo; +import org.apache.tuscany.runtime.webapp.WebappRuntimeInfo; + +/** + * @author Andy Piper + */ +public class SpringWebappRuntimeInfo extends SpringRuntimeInfo implements WebappRuntimeInfo { + public SpringWebappRuntimeInfo(File appRootDir, XmlWebApplicationContext applicationContext) { + super(appRootDir, applicationContext); + } + + public ServletContext getServletContext() { + return ((WebApplicationContext) getApplicationContext()).getServletContext(); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/DefaultScaAdapter.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/DefaultScaAdapter.java new file mode 100644 index 0000000000..e2071e27c3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/DefaultScaAdapter.java @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 11-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca; + +/** + * @author Adrian Colyer + * @since 2.0 + */ +public class DefaultScaAdapter implements ScaAdapter { + + public Object getServiceReference(String referenceName, + Class referenceType, + String moduleName, + String defaultServiceName) { + // TODO + return new Object(); + } + + public Object getPropertyReference(String propertyName, Class propertyType, String moduleName) { + // TODO + return new Object(); + } + + public void publishAsService(Object serviceImplementation, + Class serviceInterface, + String serviceName, + String moduleName) { + // TODO + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapter.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapter.java new file mode 100644 index 0000000000..e5aae6f0a2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapter.java @@ -0,0 +1,45 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 11-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca; + +/** + * Encapsulates interaction with an SCA runtime + * + * @author Adrian Colyer + * @since 2.0 + */ +public interface ScaAdapter { + + Object getServiceReference( + String referenceName, + Class referenceType, + String moduleName, + String defaultServiceName); + + Object getPropertyReference( + String propertyName, + Class propertyType, + String moduleName); + + void publishAsService( + Object serviceImplementation, + Class serviceInterface, + String serviceName, + String moduleName); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapterAware.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapterAware.java new file mode 100644 index 0000000000..abe975c936 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapterAware.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.springframework.sca; + +/** + * /** Interface that enables beans to find the ScaAdapter they are defined with. + * <p/> + * Note that in most circumstances there is no need for a bean to implement this interface. + * + * @author Andy Piper + * @since 2.1 + */ +public interface ScaAdapterAware { + void setScaAdapter(ScaAdapter adapter); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapterPostProcessor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapterPostProcessor.java new file mode 100644 index 0000000000..b07be8f452 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaAdapterPostProcessor.java @@ -0,0 +1,52 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.springframework.sca; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; + +/** + * @author Andy Piper + * @since 2.1 + */ +public class ScaAdapterPostProcessor implements BeanPostProcessor { + private ScaAdapter scaAdapter; + + public ScaAdapterPostProcessor(ScaAdapter adapter) { + this.scaAdapter = adapter; + } + + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + if (bean instanceof ScaAdapterAware) { + if (this.scaAdapter == null) { + throw new IllegalStateException("Cannot satisfy ScaAdapterAware for bean '" + + beanName + "' without ScaAdapater"); + } + ((ScaAdapterAware) bean).setScaAdapter(scaAdapter); + } + return bean; + } + + public Object postProcessAfterInitialization(Object object, String string) throws BeansException { + return object; + } + + public ScaAdapter getScaAdapter() { + return scaAdapter; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaComposite.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaComposite.java new file mode 100644 index 0000000000..e12e763d9f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaComposite.java @@ -0,0 +1,77 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca; + +import org.springframework.beans.factory.InitializingBean; + +/** + * Bean that represents an Sca composite component. An instance of this bean is created when the <sca:composite + * module-id="xxx"/> element is declared. + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaComposite implements InitializingBean { + + private String component; + private ScaAdapter scaAdapter = new DefaultScaAdapter(); + + public String getComponent() { + return this.component; + } + + public void setComponent(String component) { + this.component = component; + } + + public void setScaAdapter(ScaAdapter scaAdapter) { + this.scaAdapter = scaAdapter; + } + + public void setScaAdapterClass(Class adapterClass) { + if (!ScaAdapter.class.isAssignableFrom(adapterClass)) { + throw new IllegalArgumentException( + "Adapter class '" + adapterClass + "' specified for ScaComposite bean " + + "does not implement the ScaApapter interface" + ); + } + try { + this.scaAdapter = (ScaAdapter) adapterClass.newInstance(); + } catch (Exception ex) { + // many exceptions may be thrown by the above, we treat them all + // the same + throw new IllegalStateException("Unable to create instance of ScaAdapter class '" + + adapterClass.getName() + "'", ex); + } + } + + public ScaAdapter getScaAdapter() { + return this.scaAdapter; + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() + */ + public void afterPropertiesSet() throws Exception { + if (this.component == null) { + throw new IllegalArgumentException("Required property moduleId was not set"); + } + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaPostProcessor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaPostProcessor.java new file mode 100644 index 0000000000..f96af00584 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaPostProcessor.java @@ -0,0 +1,147 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.sca; + +import java.beans.PropertyDescriptor; + +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.task.TaskExecutor; +import org.springframework.sca.intercept.OneWayAdvisor; +import org.springframework.sca.metadata.DeploymentMetadata; +import org.springframework.sca.metadata.Injection; +import org.springframework.sca.metadata.NoSuchServiceException; +import org.springframework.sca.metadata.ServiceMetadata; + +/** + * Spring bean post processor that looks up service metadata by name for each bean definition and performs SCA + * injection. + * <p/> + * Also performs proxying for OneWay. + * + * @author Rod Johnson + */ +public class ScaPostProcessor implements InstantiationAwareBeanPostProcessor, ApplicationContextAware { + + private DeploymentMetadata deploymentMetadata; + + private ApplicationContext applicationContext; + + private TaskExecutor taskExecutor; + + //private ScaAdapter scaAdapter; + + + /** + * @param taskExecutor The taskExecutor to set. + */ + public void setTaskExecutor(TaskExecutor taskExecutor) { + this.taskExecutor = taskExecutor; + } + + // TODO would process side files when container starts up + + public void setDeploymentMetadata(DeploymentMetadata deploymentMetadata) { + this.deploymentMetadata = deploymentMetadata; + } + + /** + * @param scaAdapter the ScaAdapter for use to export services if necessary + */ + public void setScaAdapter(ScaAdapter scaAdapter) { + //this.scaAdapter = scaAdapter; + } + + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + public Object postProcessBeforeInstantiation(Class beanClass, + String beanName) throws BeansException { + return null; + } + + public boolean postProcessAfterInstantiation(Object bean, String beanName) + throws BeansException { + try { + ServiceMetadata smd = deploymentMetadata.getServiceMetadata(beanName); + doScaInjection(bean, smd); + } catch (NoSuchServiceException ex) { + // + } + return true; + } + + public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, + String beanName) throws BeansException { + return pvs; + } + + public PropertyValues postProcessPropertyValues(PropertyValues propertyValues, Object object, String string) + throws BeansException { + return propertyValues; + } + + protected void doScaInjection(Object bean, ServiceMetadata smd) { + for (Injection injection : smd.getInjections()) { + injection.apply(applicationContext, bean); + } + } + + public Object postProcessBeforeInitialization(Object bean, String beanName) + throws BeansException { + return bean; + } + + public Object postProcessAfterInitialization(Object bean, String beanName) + throws BeansException { + try { + ServiceMetadata smd = deploymentMetadata.getServiceMetadata(beanName); + return createScaProxy(bean, smd); + } catch (NoSuchServiceException ex) { + return bean; + } + + // TODO validate required injections here or earlier + + // TODO publish if necessary, using adapter + } + + protected Object createScaProxy(Object bean, ServiceMetadata smd) { + ProxyFactory pf = new ProxyFactory(bean); + for (Class intf : smd.getServiceInterfaces()) { + pf.addInterface(intf); + } + +//pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR); +//pf.addAdvisor(new ExposeBeanNameAdvisor(smd.getServiceName())); + // TODO enforce call by value + + if (!smd.getOneWayMethods().isEmpty()) { + pf.addAdvisor(new OneWayAdvisor(smd, this.taskExecutor)); + } + + return pf.getProxy(); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaPropertyProxyFactoryBean.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaPropertyProxyFactoryBean.java new file mode 100644 index 0000000000..e89072466a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaPropertyProxyFactoryBean.java @@ -0,0 +1,123 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; + +/** + * Factory bean that returns a reference to an SCA property obtained by asking the SCA runtime for the property with the + * given name for the given component. + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaPropertyProxyFactoryBean implements InitializingBean, FactoryBean { + + /** + * the type of the property + */ + private Class propertyType; + + /** + * the name of the property to look up + */ + private String propertyName; + + /** + * the SCA component we should present ourselves as when asking for a service reference + */ + private ScaComposite scaComposite; + + private Object resolvedPropertyVal; + + public void setPropertyType(Class serviceType) { + this.propertyType = serviceType; + } + + public Class getPropertyType() { + return this.propertyType; + } + + public void setPropertyName(String name) { + this.propertyName = name; + } + + public String getPropertyName() { + return this.propertyName; + } + + public void setScaComposite(ScaComposite scaComposite) { + this.scaComposite = scaComposite; + } + + public ScaComposite getScaComposite() { + return this.scaComposite; + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() + */ + public void afterPropertiesSet() throws Exception { + if (this.propertyType == null) { + throw new IllegalArgumentException("Required property serviceType was not set"); + } + if (this.scaComposite == null) { + throw new IllegalArgumentException("Required property scaComposite was not set"); + } + if (this.propertyName == null) { + throw new IllegalArgumentException("Required property referenceName was not set"); + } + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ + public Object getObject() throws Exception { + if (this.resolvedPropertyVal != null) { + return this.resolvedPropertyVal; + } + + String moduleName = this.scaComposite.getComponent(); + // TODO: AMC is there any merit in proxying this with a lazy target source? + Object propertyVal = + this.scaComposite.getScaAdapter().getPropertyReference(this.propertyName, this.propertyType, moduleName); + if (!this.propertyType.isAssignableFrom(propertyVal.getClass())) { + throw new IllegalStateException("Property value '" + propertyVal.toString() + "'" + + " of type '" + propertyVal.getClass().getName() + "' " + + " is not of expected type '" + this.propertyType.getName() + "'"); + } + this.resolvedPropertyVal = propertyVal; + return this.resolvedPropertyVal; + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ + public Class getObjectType() { + return this.propertyType; + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#isSingleton() + */ + public boolean isSingleton() { + return true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaServiceExporter.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaServiceExporter.java new file mode 100644 index 0000000000..0155dd9646 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaServiceExporter.java @@ -0,0 +1,105 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.InitializingBean; + +/** + * Exposes a bean instance to SCA to using the given service name. + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaServiceExporter implements InitializingBean, BeanFactoryAware, ScaAdapterAware { + + /** + * the name of the service we want to advertise + */ + private String serviceName; + + /** + * the type the service should be published with + */ + private Class serviceType; + + /** + * the bean to be published + */ + private Object target; + + /** + * for resolving the bean name + */ + private BeanFactory beanFactory; + private ScaAdapter scaAdapter; + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getServiceName() { + return this.serviceName; + } + + public void setServiceType(Class serviceType) { + this.serviceType = serviceType; + } + + public Class getServiceType() { + return this.serviceType; + } + + public void setTarget(Object targetBean) { + this.target = targetBean; + } + + public Object getTarget() { + return this.target; + } + + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + } + + public void afterPropertiesSet() throws Exception { + if (this.serviceType == null) { + throw new IllegalArgumentException("Required property serviceType was not set"); + } + if (this.target == null) { + throw new IllegalArgumentException("Required property target was not set"); + } + if (this.beanFactory == null) { + throw new IllegalArgumentException("Required property beanFactory was not set"); + } + if (this.serviceName == null) { + throw new IllegalArgumentException("Required property serviceName was not set"); + } + publishScaService(); + } + + private void publishScaService() { + scaAdapter.publishAsService(target, serviceType, serviceName, null); + } + + public void setScaAdapter(ScaAdapter adapter) { + this.scaAdapter = adapter; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaServiceProxyFactoryBean.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaServiceProxyFactoryBean.java new file mode 100644 index 0000000000..01ca5671d4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/ScaServiceProxyFactoryBean.java @@ -0,0 +1,144 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +/** + * Factory bean that returns a reference to an SCA service obtained by asking the SCA runtime for the service with the + * given name for the given component. + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaServiceProxyFactoryBean + implements InitializingBean, FactoryBean, ApplicationContextAware, ScaAdapterAware { + + /** + * the public interface type of the service (may be a class...) + */ + private Class serviceType; + + /** + * the name of the reference to look up + */ + private String referenceName; + + /** + * the default service name to resolve the reference too + */ + private String defaultServiceName; + + private Object resolvedServiceReference; + private ApplicationContext applicationContext; + //private ScaAdapter scaAdapter; + + public void setServiceType(Class serviceType) { + this.serviceType = serviceType; + } + + public Class getServiceType() { + return this.serviceType; + } + + public void setReferenceName(String name) { + this.referenceName = name; + } + + public String getReferenceName() { + return this.referenceName; + } + + public void setDefaultServiceName(String defaultService) { + this.defaultServiceName = defaultService; + } + + public String getDefaultServiceName() { + return this.defaultServiceName; + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() + */ + public void afterPropertiesSet() throws Exception { + if (this.serviceType == null) { + throw new IllegalArgumentException("Required property serviceType was not set"); + } + if (this.referenceName == null) { + throw new IllegalArgumentException("Required property referenceName was not set"); + } + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ + public Object getObject() throws Exception { + if (this.resolvedServiceReference != null) { + return this.resolvedServiceReference; + } + + // TODO: AMC is there any merit in proxying this with a lazy target source? + // should the returned service ref be proxied? Only seems to add value + // if SCA gives us any lifecycle events we can subscribe to and take + // meaningful action on... + // See OsgiServiceProxyFactoryBean for an example of how to do the + // proxying if needed. + Object scaServiceRef; + if (this.applicationContext.getParent() == null) { + return null; + } + + if (!this.applicationContext.getParent().containsBean(this.referenceName)) { + return new Object(); + //scaServiceRef = this.applicationContext.getParent().getBean(this.defaultServiceName); + } else { + scaServiceRef = this.applicationContext.getParent().getBean(this.referenceName); + } + if (!this.serviceType.isAssignableFrom(scaServiceRef.getClass())) { + throw new IllegalStateException("..."); + } + this.resolvedServiceReference = scaServiceRef; + return this.resolvedServiceReference; + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ + public Class getObjectType() { + return this.serviceType; + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#isSingleton() + */ + public boolean isSingleton() { + return false; + } + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + public void setScaAdapter(ScaAdapter adapter) { + // this.scaAdapter = adapter; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaCompositeBeanDefinitionParser.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaCompositeBeanDefinitionParser.java new file mode 100644 index 0000000000..9c6ac633f7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaCompositeBeanDefinitionParser.java @@ -0,0 +1,67 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.sca.ScaComposite; + +/** + * Parser for <sca:composite> elements + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaCompositeBeanDefinitionParser implements BeanDefinitionParser { + + static final String SCA_COMPOSITE_BEAN_NAME = "scaComposite"; + private static final String MODULE_ATTRIBUTE_NAME = "component"; + private static final String MODULE_ID = "component"; + private static final String ADAPTER_ATTRIBUTE = "sca-adapter-class"; + private static final String ADAPTER_CLASS_PROPERTY = "scaAdapterClass"; + + public BeanDefinition parse(Element element, ParserContext parserContext) { + BeanDefinitionRegistry registry = parserContext.getRegistry(); + if (registry.containsBeanDefinition(SCA_COMPOSITE_BEAN_NAME)) { + throw new IllegalArgumentException( + "At most one <sca:composite> element can be declared in a bean factory"); + } + BeanDefinition beanDef = createScaCompositeBeanDefinition(element); + registry.registerBeanDefinition(SCA_COMPOSITE_BEAN_NAME, beanDef); + return beanDef; + } + + private BeanDefinition createScaCompositeBeanDefinition(Element element) { + RootBeanDefinition beanDefinition = new RootBeanDefinition(); + beanDefinition.setBeanClass(ScaComposite.class); + MutablePropertyValues props = new MutablePropertyValues(); + props.addPropertyValue(MODULE_ID, element.getAttribute(MODULE_ATTRIBUTE_NAME)); + if (element.hasAttribute(ADAPTER_ATTRIBUTE)) { + props.addPropertyValue(ADAPTER_CLASS_PROPERTY, element.getAttribute(ADAPTER_ATTRIBUTE)); + } + beanDefinition.setPropertyValues(props); + return beanDefinition; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaContextBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaContextBuilder.java new file mode 100644 index 0000000000..3446aaf462 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaContextBuilder.java @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca.config; + +import org.springframework.beans.PropertyValue; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.sca.ScaAdapter; +import org.springframework.sca.ScaComposite; + +/** + * @author Hal Hildebrand Date: Apr 11, 2006 Time: 4:33:33 PM + */ +public class ScaContextBuilder { + private static final String MODULE_ID = "moduleId"; + + private static final String SCA_ADAPTER = "scaAdapter"; + + private static final String SCA_COMPOSITE_BEAN_NAME = "scaComposite"; + + private String moduleId; + + private ScaAdapter scaAdapter; + + public String getModuleId() { + return this.moduleId; + } + + public void setModuleId(String moduleId) { + this.moduleId = moduleId; + } + + public void setScaAdapter(ScaAdapter scaAdapter) { + this.scaAdapter = scaAdapter; + } + + public ScaAdapter getScaAdapter() { + return this.scaAdapter; + } + + public ApplicationContext construct() { + GenericApplicationContext parent = new GenericApplicationContext(); + BeanDefinition bd = new RootBeanDefinition(ScaComposite.class, true); + + bd.getPropertyValues().addPropertyValue(new PropertyValue(MODULE_ID, moduleId)); + bd.getPropertyValues().addPropertyValue(new PropertyValue(SCA_ADAPTER, scaAdapter)); + parent.registerBeanDefinition(SCA_COMPOSITE_BEAN_NAME, bd); + parent.refresh(); + return parent; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaNamespaceHandler.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaNamespaceHandler.java new file mode 100644 index 0000000000..878267813a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaNamespaceHandler.java @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca.config; + +import org.springframework.beans.factory.xml.NamespaceHandlerSupport; + +/** + * Handler for the <sca:> namespace. Handles: <ul> <li><sca:composite module="xxxxx"/></li> + * <li><sca:reference name="xxx" type="yyy" default-service="zzz"/></li> <li><sca:property name="xxx" + * type="yyy"/></li> <li><sca:service name="xxx" type="yyyy" target="zzz"/> </ul> + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaNamespaceHandler extends NamespaceHandlerSupport { + + public ScaNamespaceHandler() { + // FIXME JFM + init(); + } + + public final void init() { + registerBeanDefinitionParser("composite", new ScaCompositeBeanDefinitionParser()); + registerBeanDefinitionParser("reference", new ScaReferenceBeanDefinitionParser()); + registerBeanDefinitionParser("property", new ScaPropertyBeanDefinitionParser()); + registerBeanDefinitionParser("service", new ScaServiceBeanDefinitionParser()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaPropertyBeanDefinitionParser.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaPropertyBeanDefinitionParser.java new file mode 100644 index 0000000000..55413b69da --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaPropertyBeanDefinitionParser.java @@ -0,0 +1,63 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.sca.ScaPropertyProxyFactoryBean; + +/** + * Parser for the <sca:property/> element + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaPropertyBeanDefinitionParser implements BeanDefinitionParser { + + private static final String PROPERTY_NAME_ATTRIBUTE = "name"; + private static final String PROPERTY_NAME_PROPERTY = "propertyName"; + private static final String PROPERTY_TYPE_PROPERTY = "propertyType"; + private static final String TYPE_ATTRIBUTE = "type"; + private static final String ID_ATTRIBUTE = "id"; + + public BeanDefinition parse(Element element, ParserContext parserContext) { + // needs service type, reference name, sca component, and optionally default service name + BeanDefinitionRegistry registry = parserContext.getRegistry(); + String beanName = element.getAttribute(ID_ATTRIBUTE); + BeanDefinition beanDef = createBeanDefinition(element); + registry.registerBeanDefinition(beanName, beanDef); + return beanDef; + } + + private BeanDefinition createBeanDefinition(Element element) { + RootBeanDefinition beanDefinition = new RootBeanDefinition(); + beanDefinition.setBeanClass(ScaPropertyProxyFactoryBean.class); + MutablePropertyValues props = new MutablePropertyValues(); + props.addPropertyValue(PROPERTY_NAME_PROPERTY, element.getAttribute(PROPERTY_NAME_ATTRIBUTE)); + props.addPropertyValue(PROPERTY_TYPE_PROPERTY, element.getAttribute(TYPE_ATTRIBUTE)); + beanDefinition.setPropertyValues(props); + return beanDefinition; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaReferenceBeanDefinitionParser.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaReferenceBeanDefinitionParser.java new file mode 100644 index 0000000000..4f4d196571 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaReferenceBeanDefinitionParser.java @@ -0,0 +1,66 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.sca.ScaServiceProxyFactoryBean; + +/** + * Parser for the <sca:reference> element + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaReferenceBeanDefinitionParser implements BeanDefinitionParser { + + private static final String REFERENCE_NAME_ATTRIBUTE = "name"; + private static final String REFERENCE_NAME_PROPERTY = "referenceName"; + private static final String TYPE_ATTRIBUTE = "type"; + private static final String SERVICE_TYPE_PROPERTY = "serviceType"; + private static final String DEFAULT_SERVICE_ATTRIBUTE = "default"; + private static final String DEFAULT_SERVICE_PROPERTY = "defaultServiceName"; + + public BeanDefinition parse(Element element, ParserContext parserContext) { + // needs service type, reference name, sca component, and optionally default service name + BeanDefinitionRegistry registry = parserContext.getRegistry(); + String referenceName = element.getAttribute(REFERENCE_NAME_ATTRIBUTE); + BeanDefinition beanDef = createBeanDefinition(element); + registry.registerBeanDefinition(referenceName, beanDef); + return beanDef; + } + + private BeanDefinition createBeanDefinition(Element element) { + RootBeanDefinition beanDefinition = new RootBeanDefinition(); + beanDefinition.setBeanClass(ScaServiceProxyFactoryBean.class); + MutablePropertyValues props = new MutablePropertyValues(); + props.addPropertyValue(REFERENCE_NAME_PROPERTY, element.getAttribute(REFERENCE_NAME_ATTRIBUTE)); + props.addPropertyValue(SERVICE_TYPE_PROPERTY, element.getAttribute(TYPE_ATTRIBUTE)); + if (element.hasAttribute(DEFAULT_SERVICE_ATTRIBUTE)) { + props.addPropertyValue(DEFAULT_SERVICE_PROPERTY, element.getAttribute(DEFAULT_SERVICE_ATTRIBUTE)); + } + beanDefinition.setPropertyValues(props); + return beanDefinition; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaServiceBeanDefinitionParser.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaServiceBeanDefinitionParser.java new file mode 100644 index 0000000000..5867236faa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/config/ScaServiceBeanDefinitionParser.java @@ -0,0 +1,65 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Created on 10-Apr-2006 by Adrian Colyer + */ +package org.springframework.sca.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.sca.ScaServiceExporter; + +/** + * Parser for the <sca:service/> element + * + * @author Adrian Colyer + * @since 2.0 + */ +public class ScaServiceBeanDefinitionParser implements BeanDefinitionParser { + + private static final String SERVICE_NAME_ATTRIBUTE = "name"; + private static final String TYPE_ATTRIBUTE = "type"; + private static final String TARGET_ATTRIBUTE = "target"; + private static final String SERVICE_NAME_PROPERTY = "serviceName"; + private static final String SERVICE_TYPE_PROPERTY = "serviceType"; + private static final String TARGET_PROPERTY = "target"; + + public BeanDefinition parse(Element element, ParserContext parserContext) { + BeanDefinitionRegistry registry = parserContext.getRegistry(); + String serviceName = element.getAttribute(SERVICE_NAME_ATTRIBUTE); + BeanDefinition beanDef = createBeanDefinition(element); + registry.registerBeanDefinition(serviceName, beanDef); + return beanDef; + } + + private BeanDefinition createBeanDefinition(Element element) { + RootBeanDefinition beanDefinition = new RootBeanDefinition(); + beanDefinition.setBeanClass(ScaServiceExporter.class); + MutablePropertyValues props = new MutablePropertyValues(); + props.addPropertyValue(SERVICE_TYPE_PROPERTY, element.getAttribute(TYPE_ATTRIBUTE)); + props.addPropertyValue(TARGET_PROPERTY, new RuntimeBeanReference(element.getAttribute(TARGET_ATTRIBUTE))); + props.addPropertyValue(SERVICE_NAME_PROPERTY, element.getAttribute(SERVICE_NAME_ATTRIBUTE)); + beanDefinition.setPropertyValues(props); + return beanDefinition; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/intercept/OneWayAdvisor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/intercept/OneWayAdvisor.java new file mode 100644 index 0000000000..60bf2a344d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/intercept/OneWayAdvisor.java @@ -0,0 +1,82 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sca.intercept; + +import java.lang.reflect.Method; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.framework.ReflectiveMethodInvocation; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.aop.support.StaticMethodMatcherPointcut; +import org.springframework.core.task.TaskExecutor; +import org.springframework.sca.metadata.ServiceMetadata; + +/** + * An AOP Alliance MethodInterceptor, rather than AspectJ aspect, as there's no value in typed pointcuts. Oh, if it were + * only annotations... + * + * @author Rod Johnson + */ + +public class OneWayAdvisor extends DefaultPointcutAdvisor { + + private TaskExecutor taskExecutor; + + private final ServiceMetadata smd; + + public OneWayAdvisor(final ServiceMetadata aSmd, TaskExecutor taskExecutor) { + this.smd = aSmd; + setPointcut(new StaticMethodMatcherPointcut() { + public boolean matches(Method method, Class targetClass) { + for (Method m : smd.getOneWayMethods()) { + if (m.getName().equals(method.getName())) { + return true; + } + } + return false; + } + }); + setAdvice(new OneWayInterceptor()); + this.taskExecutor = taskExecutor; + } + + + private class OneWayInterceptor implements MethodInterceptor { + public Object invoke(MethodInvocation mi) throws Throwable { + try { + // TODO this is not right + ReflectiveMethodInvocation rmi = (ReflectiveMethodInvocation) mi; + final MethodInvocation clone = rmi.invocableClone(); + System.out.println("EXECUTE DEFERRED"); + taskExecutor.execute(new Runnable() { + public void run() { + try { + clone.proceed(); + } catch (Throwable ex) { + // TODO + throw new UnsupportedOperationException(); + } + } + }); + } catch (Throwable t) { + t.printStackTrace(); + } + return null; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/AnnotationServiceMetadata.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/AnnotationServiceMetadata.java new file mode 100644 index 0000000000..9a04831ab8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/AnnotationServiceMetadata.java @@ -0,0 +1,95 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sca.metadata; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.LinkedList; +import java.util.List; + +import org.osoa.sca.annotations.ComponentName; +import org.osoa.sca.annotations.OneWay; +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Service; + +import org.springframework.util.ReflectionUtils; + +/** + * TODO not the way to get this + * + * @author Rod Johnson + */ +public class AnnotationServiceMetadata implements ServiceMetadata { + + private final String name; + + private final Class<?> serviceClass; + + public AnnotationServiceMetadata(String name, Class<?> serviceClass) throws NoSuchServiceException { + if (!serviceClass.isAnnotationPresent(Service.class)) { + throw new NoSuchServiceException(); + } + this.name = name; + this.serviceClass = serviceClass; + } + + public String getServiceName() { + return name; + } + + public Class<?>[] getServiceInterfaces() { + return serviceClass.getAnnotation(Service.class).interfaces(); + } + + public List<Method> getOneWayMethods() { + List<Method> oneWayMethods = new LinkedList<Method>(); + for (Method m : serviceClass.getMethods()) { + if (m.isAnnotationPresent(OneWay.class)) { + oneWayMethods.add(m); + } + } + + // TODO fields + + return oneWayMethods; + } + + public List<Injection> getInjections() { + final List<Injection> injections = new LinkedList<Injection>(); + for (Method m : serviceClass.getMethods()) { + if (m.isAnnotationPresent(Property.class)) { + injections.add(new MethodInjection(m)); + } + } + + // TODO fields propertly + + ReflectionUtils.doWithFields(serviceClass, new ReflectionUtils.FieldCallback() { + public void doWith(Field f) throws IllegalArgumentException { + if (f.isAnnotationPresent(ComponentName.class)) { + Injection componentNameInjection = new FieldInjection(f); + componentNameInjection.setLiteralValue(name); + injections.add(componentNameInjection); + } + } + }); + + return injections; + } + + // TODO reference + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/BeanFactoryDeploymentMetadata.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/BeanFactoryDeploymentMetadata.java new file mode 100644 index 0000000000..b819ad8f8d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/BeanFactoryDeploymentMetadata.java @@ -0,0 +1,55 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.sca.metadata; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; + +/** + * DeploymentMetadata implementation backed by Spring BeanFactory metadata + * + * @author Rod Johnson + */ +public class BeanFactoryDeploymentMetadata implements BeanFactoryAware, DeploymentMetadata { + + private BeanFactory beanFactory; + + private Map<String, ServiceMetadata> serviceNameToMetadataMap = new HashMap<String, ServiceMetadata>(); + + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + } + + + /* (non-Javadoc) + * @see org.springframework.sca.metadata.DeploymentMetadata#getServiceMetadata(java.lang.String) + */ + public synchronized ServiceMetadata getServiceMetadata(String serviceName) throws NoSuchServiceException { + ServiceMetadata sm = serviceNameToMetadataMap.get(serviceName); + if (sm == null) { + Class clazz = beanFactory.getType(serviceName); + sm = new AnnotationServiceMetadata(serviceName, clazz); + serviceNameToMetadataMap.put(serviceName, sm); + } + return sm; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/DeploymentMetadata.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/DeploymentMetadata.java new file mode 100644 index 0000000000..950e5e3786 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/DeploymentMetadata.java @@ -0,0 +1,28 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.sca.metadata; + +/** + * Source of ServiceMetadata by name + * + * @author Rod Johnson + */ +public interface DeploymentMetadata { + + ServiceMetadata getServiceMetadata(String serviceName) throws NoSuchServiceException; + +}
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/FieldInjection.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/FieldInjection.java new file mode 100644 index 0000000000..3d9f1b6e79 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/FieldInjection.java @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sca.metadata; + +import java.lang.reflect.Field; + +import org.osoa.sca.annotations.Reference; + +/** + * @author Rod Johnson + */ +public class FieldInjection extends Injection { + + private final Field field; + + public FieldInjection(Field field, String lookupName) { + super(lookupName); + this.field = field; + } + + public FieldInjection(Field field) { + Reference annotation = field.getAnnotation(Reference.class); + + this.field = field; + + if (annotation == null) { + //throw new IllegalArgumentException("Field " + field + " not annotated"); + return; + } + + if ("".equals(annotation.name())) { + setLookupName(field.getName()); + } else { + setLookupName(annotation.name()); + } + } + + @Override + protected void injectValue(Object target, Object value) { + try { + if (!field.isAccessible()) { + field.setAccessible(true); + } + field.set(target, value); + } catch (IllegalArgumentException ex) { + // TODO + throw new UnsupportedOperationException(); + } catch (IllegalAccessException ex) { + // TODO + ex.printStackTrace(); + throw new UnsupportedOperationException(); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/Injection.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/Injection.java new file mode 100644 index 0000000000..2e81516d56 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/Injection.java @@ -0,0 +1,76 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sca.metadata; + +import org.springframework.beans.factory.BeanFactory; + +/** + * @author Rod Johnson + */ +public abstract class Injection { + + private String lookupName; + + /** + * Is it a literal value? + */ + private boolean literal; + + /** + * Literal value if it's a literal + */ + private Object literalValue; + + protected Injection() { + + } + + protected Injection(String lookupName) { + this.lookupName = lookupName; + } + + public Object getLiteralValue() { + return literalValue; + } + + public void setLiteralValue(Object literalValue) { + this.literal = true; + this.literalValue = literalValue; + } + + public boolean isLiteral() { + return literal; + } + + protected void setLookupName(String lookupName) { + this.lookupName = lookupName; + } + + public String getLookupName() { + return lookupName; + } + + public void apply(BeanFactory owner, Object target) { + Object value = literalValue; + if (!isLiteral()) { + value = owner.getBean(lookupName); + } + injectValue(target, value); + } + + protected abstract void injectValue(Object target, Object value); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/MethodInjection.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/MethodInjection.java new file mode 100644 index 0000000000..df01d1428d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/MethodInjection.java @@ -0,0 +1,65 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sca.metadata; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.osoa.sca.annotations.Property; + +/** + * @author Rod Johnson + */ +public class MethodInjection extends Injection { + + private final Method method; + + public MethodInjection(Method method, String lookupName) { + super(lookupName); + this.method = method; + } + + public MethodInjection(Method method) { + // TODO reference also + Property annotation = method.getAnnotation(Property.class); + if (annotation == null) { + throw new IllegalArgumentException("Method " + method + " not annotated"); + } + this.method = method; + if ("".equals(annotation.name())) { + setLookupName(method.getName()); + } else { + setLookupName(annotation.name()); + } + } + + @Override + protected void injectValue(Object target, Object value) { + try { + method.invoke(target, value); + } catch (IllegalArgumentException ex) { + // TODO + throw new UnsupportedOperationException(); + } catch (IllegalAccessException ex) { + // TODO + throw new UnsupportedOperationException(); + } catch (InvocationTargetException ex) { + // TODO + throw new UnsupportedOperationException(); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/NoSuchServiceException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/NoSuchServiceException.java new file mode 100644 index 0000000000..b7ffdfeee6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/NoSuchServiceException.java @@ -0,0 +1,24 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.sca.metadata; + +/** + * @author Rod Johnson + */ +public class NoSuchServiceException extends Exception { + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/ServiceMetadata.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/ServiceMetadata.java new file mode 100644 index 0000000000..5d23c499e4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/java/org/springframework/sca/metadata/ServiceMetadata.java @@ -0,0 +1,56 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.sca.metadata; + +import java.lang.reflect.Method; +import java.util.List; + +/** + * Metadata for an SCA component. + * + * @author Rod Johnson + */ +public interface ServiceMetadata { + + /** + * Return the service name + * + * @return the service name of the component + */ + String getServiceName(); + + /** + * Return the service interfaces implemented by the component + * + * @return interfaces implemented by the component + */ + Class<?>[] getServiceInterfaces(); + + /** + * Return a list of OneWay methods + * + * @return never returns null + */ + List<Method> getOneWayMethods(); + + /** + * Return a list of SCA injections + * @return a list of SCA injections. Never returns null. + */ + List<Injection> getInjections(); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/sca/spring.system.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/sca/spring.system.scdl new file mode 100644 index 0000000000..cbd7138f0d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/sca/spring.system.scdl @@ -0,0 +1,40 @@ +<?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. + --> +<!-- + Spring implementation extension configuration for the launcher environment. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + + name="org.apache.tuscany.launcher.SpringImplementation"> + + <component name="spring.implementationLoader"> + <system:implementation.system class="org.apache.tuscany.container.spring.impl.SpringImplementationLoader"/> + </component> + + <component name="spring.componentTypeLoader"> + <system:implementation.system class="org.apache.tuscany.container.spring.impl.SpringComponentTypeLoader"/> + </component> + + <component name="spring.componentBuilder"> + <system:implementation.system class="org.apache.tuscany.container.spring.impl.SpringCompositeBuilder"/> + </component> + +</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/spring.handlers b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/spring.handlers new file mode 100644 index 0000000000..689b49e2ae --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/spring.handlers @@ -0,0 +1,3 @@ +http\://www.springframework.org/schema/sca=org.springframework.sca.config.ScaNamespaceHandler + + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/spring.schemas b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/spring.schemas new file mode 100644 index 0000000000..33f7004be9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/META-INF/spring.schemas @@ -0,0 +1 @@ +http\://www.springframework.org/schema/sca/spring-sca.xsd=org/springframework/sca/xml/spring-sca.xsd diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/org/springframework/sca/xml/spring-sca.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/org/springframework/sca/xml/spring-sca.xsd new file mode 100644 index 0000000000..b4eeadbb74 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/main/resources/org/springframework/sca/xml/spring-sca.xsd @@ -0,0 +1,101 @@ +<?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. +--> +<xsd:schema xmlns="http://www.springframework.org/schema/sca" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + attributeFormDefault="unqualified" + elementFormDefault="qualified" + targetNamespace="http://www.springframework.org/schema/sca"> + + <xsd:element name="composite"> + <xsd:complexType> + <xsd:attribute name="component" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="sca-adapter-class" use="optional"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="reference"> + <xsd:complexType> + <xsd:attribute name="name" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="type" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="default" use="optional"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="property"> + <xsd:complexType> + <xsd:attribute name="id" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="name" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="type" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="service"> + <xsd:complexType> + <xsd:attribute name="name" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="type" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="target" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + +</xsd:schema> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/SpringConfigSchemaTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/SpringConfigSchemaTestCase.java new file mode 100644 index 0000000000..80b22d6784 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/SpringConfigSchemaTestCase.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.container.spring; + +import junit.framework.TestCase; +import org.apache.tuscany.container.spring.config.ScaApplicationContext; +import org.apache.tuscany.container.spring.mock.TestReference; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.sca.ScaServiceExporter; +import org.springframework.sca.ScaServiceProxyFactoryBean; + +/** + * Tests the SCA extensible schema elements for Spring's XML configuration files + * + * @version $$Rev$$ $$Date$$ + */ + +public class SpringConfigSchemaTestCase extends TestCase { + + private ConfigurableApplicationContext applicationContext; + + public void setUp() { + applicationContext = + new ScaApplicationContext(null, + new ClassPathResource("org/apache/tuscany/container/spring/SpringConfigSchemaTest.xml"), null); + } + + public void testSCAService() { + ScaServiceExporter service = (ScaServiceExporter) applicationContext.getBean("fooService"); + // FIXME andyp -- this is not really right. +// TestBean service = (TestBean) applicationContext.getBean("fooService"); +// assertEquals("call me", service.echo("call me")); + } + + public void testSCAReference() { + ScaServiceProxyFactoryBean pf = (ScaServiceProxyFactoryBean) applicationContext.getBean("&fooReference"); + assertEquals("fooReference", pf.getReferenceName()); + TestReference ref = (TestReference) applicationContext.getBean("fooReference"); +// assertNotNull(ref); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/SpringTestUtils.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/SpringTestUtils.java new file mode 100644 index 0000000000..3d07c753de --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/SpringTestUtils.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.container.spring; + +import org.apache.tuscany.spi.QualifiedName; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.builder.Connector; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.WireService; + +import org.apache.tuscany.container.spring.mock.TestBeanImpl; +import org.apache.tuscany.test.ArtifactFactory; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.context.support.GenericApplicationContext; + +/** + * @version $$Rev$$ $$Date$$ + */ + +public final class SpringTestUtils { + private SpringTestUtils() { + } + + public static <T> Service createService(String name, + Class<T> serviceInterface, + CompositeComponent parent, + WireService wireService) throws InvalidServiceContractException { + Service service = new ServiceExtension(name, serviceInterface, parent, wireService); + InboundWire inboundWire = ArtifactFactory.createInboundWire(name, serviceInterface); + OutboundWire outboundWire = ArtifactFactory.createOutboundWire(name, serviceInterface); + ArtifactFactory.terminateWire(outboundWire); + service.setInboundWire(inboundWire); + service.setOutboundWire(outboundWire); + outboundWire.setTargetName(new QualifiedName("foo")); + Connector connector = ArtifactFactory.createConnector(); + connector.connect(service); + ArtifactFactory.terminateWire(inboundWire); + return service; + } + + + public static GenericApplicationContext createContext() { + GenericApplicationContext ctx = new GenericApplicationContext(); + BeanDefinition definition = new RootBeanDefinition(TestBeanImpl.class); + ctx.registerBeanDefinition("foo", definition); + return ctx; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/ReferenceInvocationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/ReferenceInvocationTestCase.java new file mode 100644 index 0000000000..ff5a564ee8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/ReferenceInvocationTestCase.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.container.spring.impl; + +import org.apache.tuscany.spi.component.Reference; + +import junit.framework.TestCase; +import org.apache.tuscany.container.spring.mock.TestBean; +import org.apache.tuscany.container.spring.mock.TestBeanImpl; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import org.springframework.beans.PropertyValue; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.StaticApplicationContext; + +/** + * Verifies wiring from a Spring bean to an SCA composite reference + * + * @version $$Rev$$ $$Date$$ + */ +public class ReferenceInvocationTestCase extends TestCase { + + public void testInvocation() throws Exception { + AbstractApplicationContext ctx = createSpringContext(); + SpringCompositeComponent parent = new SpringCompositeComponent("spring", ctx, null, null, null); + parent.start(); + TestBean referenceTarget = new TestBeanImpl(); + Reference reference = createMock(Reference.class); + expect(reference.getName()).andReturn("bar").anyTimes(); + expect(reference.isSystem()).andReturn(false).atLeastOnce(); + expect(reference.getInterface()).andStubReturn(TestBean.class); + expect(reference.getServiceInstance()).andStubReturn(referenceTarget); + replay(reference); + parent.register(reference); + ctx.getBean("foo"); + } + + private AbstractApplicationContext createSpringContext() { + StaticApplicationContext beanFactory = new StaticApplicationContext(); + RootBeanDefinition definition = new RootBeanDefinition(TestBeanImpl.class); + //REVIEW we need to figure out how to handle eager init components + definition.setLazyInit(true); + RuntimeBeanReference ref = new RuntimeBeanReference("bar"); + PropertyValue val = new PropertyValue("bean", ref); + definition.getPropertyValues().addPropertyValue(val); + beanFactory.registerBeanDefinition("foo", definition); + return beanFactory; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/ServiceInvocationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/ServiceInvocationTestCase.java new file mode 100644 index 0000000000..596d9f1181 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/ServiceInvocationTestCase.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.container.spring.impl; + +import org.apache.tuscany.spi.builder.Connector; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.QualifiedName; + +import junit.framework.TestCase; +import org.apache.tuscany.container.spring.mock.TestBean; +import org.apache.tuscany.container.spring.mock.TestBeanImpl; +import org.apache.tuscany.test.ArtifactFactory; +import static org.apache.tuscany.test.ArtifactFactory.createWireService; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.StaticApplicationContext; + +/** + * Tests a simple invocation through a service to a Spring bean + * + * @version $$Rev$$ $$Date$$ + */ +public class ServiceInvocationTestCase extends TestCase { + + public void testInvocation() throws InvalidServiceContractException { + AbstractApplicationContext springContext = createSpringContext(); + SpringCompositeComponent composite = new SpringCompositeComponent("parent", springContext, null, null, null); + InboundWire inboundWire = ArtifactFactory.createInboundWire("fooService", TestBean.class); + OutboundWire outboundWire = ArtifactFactory.createOutboundWire("fooService", TestBean.class); + outboundWire.setTargetName(new QualifiedName("foo")); + ArtifactFactory.terminateWire(outboundWire); + Service service = + new ServiceExtension("fooService", TestBean.class, composite, createWireService()); + service.setInboundWire(inboundWire); + service.setOutboundWire(outboundWire); + Connector connector = ArtifactFactory.createConnector(); + connector.connect(inboundWire, outboundWire, true); + for (InboundInvocationChain chain : inboundWire.getInvocationChains().values()) { + chain.setTargetInvoker(composite.createTargetInvoker("foo", chain.getOperation())); + } + composite.register(service); + TestBean serviceInstance = (TestBean) composite.getService("fooService").getServiceInstance(); + assertEquals("bar", serviceInstance.echo("bar")); + } + + + private AbstractApplicationContext createSpringContext() { + StaticApplicationContext beanFactory = new StaticApplicationContext(); + RootBeanDefinition definition = new RootBeanDefinition(TestBeanImpl.class); + definition.setLazyInit(true); + beanFactory.registerBeanDefinition("foo", definition); + return beanFactory; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringCompositeBuilderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringCompositeBuilderTestCase.java new file mode 100644 index 0000000000..50ce9a7b75 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringCompositeBuilderTestCase.java @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.spring.impl; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.tuscany.spi.builder.BuilderRegistry; +import org.apache.tuscany.spi.builder.Connector; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import static org.apache.tuscany.container.spring.SpringTestUtils.createContext; +import org.apache.tuscany.container.spring.mock.TestBean; +import org.apache.tuscany.container.spring.model.SpringComponentType; +import org.apache.tuscany.container.spring.model.SpringImplementation; +import org.apache.tuscany.test.ArtifactFactory; +import org.apache.tuscany.test.binding.TestBinding; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.createNiceMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class SpringCompositeBuilderTestCase extends TestCase { + + /** + * Verfies basic build of a spring context + */ + @SuppressWarnings("unchecked") + public void testBuild() throws Exception { + // Create an assembly model consisting of a component implemented by Spring + SpringImplementation impl = new SpringImplementation(new SpringComponentType(createContext())); + ComponentDefinition<SpringImplementation> componentDefinition = + new ComponentDefinition<SpringImplementation>("spring", impl); + + // Configure the mock builder registry + BuilderRegistry registry = createNiceMock(BuilderRegistry.class); + + // Test the SpringCompositeBuilder + SpringCompositeBuilder builder = new SpringCompositeBuilder(); + builder.setBuilderRegistry(registry); + CompositeComponent parent = createNiceMock(CompositeComponent.class); + DeploymentContext context = createNiceMock(DeploymentContext.class); + SpringCompositeComponent component = + (SpringCompositeComponent) builder.build(parent, componentDefinition, context); + TestBean bean = (TestBean) component.getApplicationContext().getBean("foo"); + assertEquals("call foo", bean.echo("call foo")); + } + + /** + * Verifies that the builder calls back into the registry to load services and wires them to bean targets when no + * <code>sca:service</code> tag is specified in the Spring application.xml + */ + @SuppressWarnings("unchecked") + public void testImplicitServiceWiring() throws Exception { + // Create an assembly model consisting of a component implemented by Spring + SpringImplementation impl = new SpringImplementation(createComponentType()); + ComponentDefinition<SpringImplementation> componentDefinition = + new ComponentDefinition<SpringImplementation>("spring", impl); + + // Create a service instance that the mock builder registry will return + WireService wireService = ArtifactFactory.createWireService(); + ServiceExtension serviceContext = + new ServiceExtension("fooService", TestBean.class, null, wireService); + InboundWire inboundWire = ArtifactFactory.createInboundWire("fooService", TestBean.class); + OutboundWire outboundWire = ArtifactFactory.createOutboundWire("fooService", TestBean.class); + ArtifactFactory.terminateWire(outboundWire); + serviceContext.setInboundWire(inboundWire); + serviceContext.setOutboundWire(outboundWire); + Connector connector = ArtifactFactory.createConnector(); + connector.connect(inboundWire, outboundWire, true); + + // Configure the mock builder registry + BuilderRegistry registry = createMock(BuilderRegistry.class); + expect(registry.build(isA(CompositeComponent.class), + isA(BoundServiceDefinition.class), + isA(DeploymentContext.class))).andStubReturn(serviceContext); + replay(registry); + + // Test the SpringCompositeBuilder + SpringCompositeBuilder builder = new SpringCompositeBuilder(); + builder.setWireService(wireService); + builder.setBuilderRegistry(registry); + CompositeComponent parent = createNiceMock(CompositeComponent.class); + DeploymentContext context = createNiceMock(DeploymentContext.class); + CompositeComponent component = (CompositeComponent) builder.build(parent, componentDefinition, context); + Service service = component.getService("fooService"); + TestBean bean = (TestBean) service.getServiceInstance(); + assertEquals("call foo", bean.echo("call foo")); + verify(registry); + } + + @SuppressWarnings("unchecked") + private SpringComponentType createComponentType() { + SpringComponentType componentType = new SpringComponentType(createContext()); + BoundServiceDefinition<TestBinding> serviceDefinition = new BoundServiceDefinition<TestBinding>(); + serviceDefinition.setName("fooService"); + serviceDefinition.setBinding(new TestBinding()); + try { + serviceDefinition.setTarget(new URI("foo")); + } catch (URISyntaxException e) { + throw new AssertionError(); + } + componentType.add(serviceDefinition); + return componentType; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringCompositeComponentTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringCompositeComponentTestCase.java new file mode 100644 index 0000000000..f3ac13d030 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringCompositeComponentTestCase.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.spring.impl; + +import org.apache.tuscany.spi.component.Service; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.expect; +import org.easymock.classextension.EasyMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.AbstractApplicationContext; + +/** + * @version $Rev$ $Date$ + */ +public class SpringCompositeComponentTestCase extends TestCase { + + public void testAppContextStart() { + AbstractApplicationContext appContext = EasyMock.createMock(AbstractApplicationContext.class); + appContext.refresh(); + appContext.setParent(EasyMock.isA(ApplicationContext.class)); + appContext.start(); + replay(appContext); + SpringCompositeComponent component = new SpringCompositeComponent("spring", appContext, null, null, null); + component.start(); + verify(appContext); + } + + public void testChildStart() { + AbstractApplicationContext appContext = EasyMock.createNiceMock(AbstractApplicationContext.class); + replay(appContext); + Service service = EasyMock.createMock(Service.class); + EasyMock.expect(service.getName()).andReturn("foo").anyTimes(); + service.start(); + service.getInterface(); + EasyMock.expectLastCall().andReturn(Object.class); + expect(service.isSystem()).andReturn(false).atLeastOnce(); + replay(service); + SpringCompositeComponent component = new SpringCompositeComponent("spring", appContext, null, null, null); + component.register(service); + component.start(); + verify(service); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringInvocationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringInvocationTestCase.java new file mode 100644 index 0000000000..b110852a54 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/impl/SpringInvocationTestCase.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.container.spring.impl; + +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import org.springframework.context.ApplicationContext; + +/** + * Verifies a simple invocation on a Spring bean + * + * @version $$Rev$$ $$Date$$ + */ +public class SpringInvocationTestCase extends TestCase { + + /** + * Verifies the invoker can resolve a bean in an application context and call a method l + */ + public void testInvocation() throws Exception { + TestBean bean = createMock(TestBean.class); + bean.test("bar"); + expectLastCall(); + replay(bean); + ApplicationContext context = createMock(ApplicationContext.class); + expect(context.getBean("foo")).andReturn(bean); + replay(context); + SpringInvoker invoker = new SpringInvoker("foo", TestBean.class.getMethod("test", String.class), context); + Message msg = new MessageImpl(); + msg.setBody(new String[]{"bar"}); + invoker.invoke(msg); + verify(context); + verify(bean); + } + + + private interface TestBean { + void test(String msg); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/integration/BootstrapTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/integration/BootstrapTestCase.java new file mode 100644 index 0000000000..c5758cb2ac --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/integration/BootstrapTestCase.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.container.spring.integration; + +import org.osoa.sca.CompositeContext; +import org.osoa.sca.CurrentCompositeContext; + +import org.apache.tuscany.spi.component.Service; + +import org.apache.tuscany.container.spring.impl.SpringCompositeComponent; +import org.apache.tuscany.container.spring.mock.TestBean; +import org.apache.tuscany.test.Bootstrapper; + +/** + * Bootstraps a simple scenario where a service can invoke a Spring bean. This test case is intended to be temporary and + * replaced when the SPI test harness is finished. + * <p/> + * <bold>PLEASE DO NOT EMULATE</bold> + * + * @version $Rev$ $Date$ + */ +public class BootstrapTestCase extends Bootstrapper { + + private CompositeContext context; + + public void testDemoBoot() { + SpringCompositeComponent comp = (SpringCompositeComponent) component.getChild("Spring"); + Service service = (Service) comp.getChild("fooService"); + TestBean bean = (TestBean) service.getServiceInstance(); + bean.echo("foo"); + bean.getBean().echo("foo"); + } + + protected void setUp() throws Exception { + addExtension("spring.extension", getClass().getClassLoader().getResource("META-INF/sca/spring.system.scdl")); + super.setUp(); + context = CurrentCompositeContext.getContext(); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestBean.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestBean.java new file mode 100644 index 0000000000..1c768e53cc --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestBean.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.container.spring.mock; + +/** + * @version $$Rev$$ $$Date$$ + */ +public interface TestBean { + String echo(String msg); + + TestBean getBean(); + + void setBean(TestBean bean); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestBeanImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestBeanImpl.java new file mode 100644 index 0000000000..db04d8bcad --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestBeanImpl.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.container.spring.mock; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class TestBeanImpl implements TestBean { + + private TestBean bean; + + public TestBeanImpl() { + } + + public String echo(String msg) { + return msg; + } + + public TestBean getBean() { + return bean; + } + + public void setBean(TestBean bean) { + this.bean = bean; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestReference.java b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestReference.java new file mode 100644 index 0000000000..7d1a519be6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/java/org/apache/tuscany/container/spring/mock/TestReference.java @@ -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. + */ +package org.apache.tuscany.container.spring.mock; + +/** + * @version $$Rev$$ $$Date$$ + */ +public interface TestReference { + String echo(String msg); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/META-INF/sca/application-context.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/META-INF/sca/application-context.xml new file mode 100644 index 0000000000..6ccd3963a9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/META-INF/sca/application-context.xml @@ -0,0 +1,32 @@ +<?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. +--> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:sca="http://www.springframework.org/schema/sca" + xsi:schemaLocation=" +http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd +http://www.springframework.org/schema/sca http://www.springframework.org/schema/sca/spring-sca.xsd"> + + <bean id="testBean" class="org.apache.tuscany.container.spring.mock.TestBeanImpl" lazy-init="true"> + <property name="bean" ref="testReference"/> + </bean> + <!-- <sca:reference name="testReference" type="org.apache.tuscany.container.spring.mock.TestReference"/> --> + +</beans> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..0b2c92c667 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/META-INF/sca/default.scdl @@ -0,0 +1,37 @@ +<?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. + --> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + name="spring.test"> + + <component name="Spring"> + <implementation.spring location="META-INF/sca/application-context.xml"> + <service name="fooService"> + <binding.test/> + <interface.java class="org.apache.tuscany.container.spring.mock.TestBean"/> + <reference>testBean</reference> + </service> + <reference name="testReference"> + <interface.java class="org.apache.tuscany.container.spring.mock.TestBean"/> + <binding.test/> + </reference> + </implementation.spring> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/org/apache/tuscany/container/spring/ExplicitSpring.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/org/apache/tuscany/container/spring/ExplicitSpring.xml new file mode 100644 index 0000000000..211211511b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/org/apache/tuscany/container/spring/ExplicitSpring.xml @@ -0,0 +1,32 @@ +<?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. +--> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:sca="http://www.springframework.org/schema/sca" + xsi:schemaLocation=" +http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd +http://www.springframework.org/schema/sca http://www.springframework.org/schema/sca/spring-sca.xsd"> + + <sca:service name="fooBean" type="org.apache.tuscany.container.spring.mock.TestBeanImpl" target="testBean"/> + + <bean id="testBean" class="org.apache.tuscany.container.spring.mock.TestBeanImpl"> + </bean> + +</beans> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/org/apache/tuscany/container/spring/SpringConfigSchemaTest.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/org/apache/tuscany/container/spring/SpringConfigSchemaTest.xml new file mode 100644 index 0000000000..96a3e1ed46 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/org/apache/tuscany/container/spring/SpringConfigSchemaTest.xml @@ -0,0 +1,35 @@ +<?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. +--> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:sca="http://www.springframework.org/schema/sca" + xsi:schemaLocation=" +http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd +http://www.springframework.org/schema/sca http://www.springframework.org/schema/sca/spring-sca.xsd"> + + <bean id="testBean" class="org.apache.tuscany.container.spring.mock.TestBeanImpl"> + </bean> + + <sca:service name="fooService" type="org.apache.tuscany.container.spring.mock.TestBean" target="testBean"/> + + <sca:reference name="fooReference" type="org.apache.tuscany.container.spring.mock.TestReference"/> + + +</beans> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/test.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/test.xml new file mode 100644 index 0000000000..d438b88577 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/container.spring/src/test/resources/test.xml @@ -0,0 +1,29 @@ +<?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. +--> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:sca="http://www.springframework.org/schema/sca" + xsi:schemaLocation=" +http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd +http://www.springframework.org/schema/sca http://www.springframework.org/schema/sca/spring-sca.xsd"> + + <bean id="testBean" class="org.apache.tuscany.container.spring.mock.TestBeanImpl"/> + +</beans> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/containers/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/pom.xml new file mode 100644 index 0000000000..4bd5db50a5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/containers/pom.xml @@ -0,0 +1,84 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.tuscany.sca.services.containers</groupId> + <artifactId>parent</artifactId> + <packaging>pom</packaging> + <name>Tuscany SCA Containers</name> + + <!-- definition of repositories where the parent pom can be found --> + <repositories> + <repository> + <id>apache.snapshots</id> + <name>Apache Snapshot Repository</name> + <url>http://people.apache.org/repo/m2-snapshot-repository</url> + <releases> + <enabled>false</enabled> + </releases> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>apache.incubator</id> + <name>Apache Incubator Repository</name> + <url>http://people.apache.org/repo/m2-incubating-repository/</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + + <profiles> + <profile> + <id>full</id> + <activation> + <activeByDefault>true</activeByDefault> + </activation> + <modules> + <module>container.groovy</module> + <module>container.javascript</module> + <module>container.ruby</module> + <module>container.spring</module> + </modules> + </profile> + <profile> + <id>release</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <modules> + <module>container.javascript</module> + <module>container.ruby</module> + <module>container.spring</module> + </modules> + </profile> + </profiles> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/LICENSE.txt new file mode 100755 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/pom.xml new file mode 100755 index 0000000000..c92cb94b88 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/pom.xml @@ -0,0 +1,76 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>databinding-axiom</artifactId> + <name>Apache Tuscany Data Binding for Axiom</name> + <description>Tuscany Axiom Data Binding</description> + + <repositories> + <repository> + <id>apache.m1.snapshots</id> + <name>Apache M1 Snapshot Repository</name> + <url>http://people.apache.org/repo/m1-snapshot-repository</url> + <layout>legacy</layout> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + </repositories> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-api</artifactId> + </dependency> + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-impl</artifactId> + <scope>runtime</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + + <dependency> + <groupId>woodstox</groupId> + <artifactId>wstx-asl</artifactId> + </dependency> + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <version>1.0.4</version> + <scope>test</scope> + </dependency> + </dependencies> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/AxiomDataBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/AxiomDataBinding.java new file mode 100644 index 0000000000..6a43d25847 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/AxiomDataBinding.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.databinding.axiom; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.spi.databinding.DataBinding; +import org.apache.tuscany.spi.databinding.WrapperHandler; +import org.apache.tuscany.spi.databinding.extension.DataBindingExtension; +import org.osoa.sca.annotations.Service; + +/** + * DataBinding for AXIOM + */ +@Service(DataBinding.class) +public class AxiomDataBinding extends DataBindingExtension { + + public static final String NAME = OMElement.class.getName(); + + public AxiomDataBinding() { + super(OMElement.class); + } + + /** + * @see org.apache.tuscany.spi.databinding.extension.DataBindingExtension#getWrapperHandler() + */ + @Override + public WrapperHandler getWrapperHandler() { + return new OMElementWrapperHandler(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2Object.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2Object.java new file mode 100644 index 0000000000..91b1f4da90 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2Object.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.axiom; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.SimpleType2JavaTransformer; +import org.osoa.sca.annotations.Service; + +/** + * Transformer to convert data from a simple java bject to OMElement + */ +@Service(Transformer.class) +public class OMElement2Object extends SimpleType2JavaTransformer<OMElement> { + + @Override + protected String getText(OMElement source) { + return source.getText(); + } + + public Class getSourceType() { + return OMElement.class; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2String.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2String.java new file mode 100755 index 0000000000..52be08537d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2String.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.databinding.axiom; + +import java.io.StringWriter; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +/** + * Transformer to convert data from an OMElement to XML String + */ +@Service(Transformer.class) +public class OMElement2String extends TransformerExtension<OMElement, String> implements PullTransformer<OMElement, String> { + // private XmlOptions options; + + public String transform(OMElement source, TransformationContext context) { + try { + StringWriter writer = new StringWriter(); + source.serialize(writer); + return writer.toString(); + } catch (XMLStreamException e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return OMElement.class; + } + + public Class getTargetType() { + return String.class; + } + + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2XMLStreamReader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2XMLStreamReader.java new file mode 100755 index 0000000000..343408a027 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElement2XMLStreamReader.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.databinding.axiom; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +@Service(Transformer.class) +public class OMElement2XMLStreamReader extends TransformerExtension<OMElement, XMLStreamReader> implements PullTransformer<OMElement, XMLStreamReader> { + // private XmlOptions options; + + public XMLStreamReader transform(OMElement source, TransformationContext context) { + return source.getXMLStreamReader(); + } + + public Class getSourceType() { + return OMElement.class; + } + + public Class getTargetType() { + return XMLStreamReader.class; + } + + public int getWeight() { + return 10; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElementWrapperHandler.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElementWrapperHandler.java new file mode 100644 index 0000000000..0ba2863735 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/OMElementWrapperHandler.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.databinding.axiom; + +import java.util.Iterator; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.WrapperHandler; +import org.apache.tuscany.spi.idl.ElementInfo; + +/** + * OMElement wrapper handler implementation + */ +public class OMElementWrapperHandler implements WrapperHandler<OMElement> { + + private OMFactory factory; + + public OMElementWrapperHandler() { + super(); + this.factory = OMAbstractFactory.getOMFactory(); + } + + public OMElement create(ElementInfo element, TransformationContext context) { + OMElement wrapper = factory.createOMElement(element.getQName(), null); + return wrapper; + } + + public Object getChild(OMElement wrapper, int i, ElementInfo element) { + int index = 0; + for (Iterator e = wrapper.getChildElements(); e.hasNext();) { + OMElement child = (OMElement) e.next(); + if (index != i) { + index++; + continue; + } + if (child.getQName().equals(element.getQName())) { + return child; + } + } + return null; + } + + public void setChild(OMElement wrapper, int i, ElementInfo childElement, Object value) { + wrapper.addChild((OMElement) value); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/Object2OMElement.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/Object2OMElement.java new file mode 100644 index 0000000000..5416b5239e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/Object2OMElement.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.databinding.axiom; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.Java2SimpleTypeTransformer; +import org.apache.tuscany.spi.idl.ElementInfo; +import org.osoa.sca.annotations.Service; + +/** + * Transformer to convert data from an simple OMElement to Java Object + */ +@Service(Transformer.class) +public class Object2OMElement extends Java2SimpleTypeTransformer<OMElement> { + + private OMFactory factory; + + public Object2OMElement() { + super(); + factory = OMAbstractFactory.getOMFactory(); + } + + protected OMElement createElement(ElementInfo element, String text, TransformationContext context) { + OMElement omElement = factory.createOMElement(element.getQName(), null); + factory.createOMText(omElement, text); + return omElement; + } + + @Override + public Class getTargetType() { + return OMElement.class; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/String2OMElement.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/String2OMElement.java new file mode 100755 index 0000000000..59ac5423d7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/String2OMElement.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.axiom; + +import java.io.ByteArrayInputStream; + +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.apache.tuscany.spi.model.DataType; +import org.osoa.sca.annotations.Service; + +@Service(Transformer.class) +public class String2OMElement extends TransformerExtension<String, OMElement> implements + PullTransformer<String, OMElement> { + + @SuppressWarnings("unchecked") + public OMElement transform(String source, TransformationContext context) { + try { + StAXOMBuilder builder = new StAXOMBuilder(new ByteArrayInputStream(source.getBytes())); + OMElement element = builder.getDocumentElement(); + adjustElementName(context, element); + return element; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + /** + * @param context + * @param element + */ + private void adjustElementName(TransformationContext context, OMElement element) { + if (context != null) { + DataType dataType = context.getTargetDataType(); + Object targetQName = dataType == null ? null : dataType.getLogical(); + if (!(targetQName instanceof QName)) { + return; + } + if (!element.getQName().equals(targetQName)) { + // TODO: Throw expection or switch to the new Element + OMFactory factory = OMAbstractFactory.getOMFactory(); + QName name = (QName)targetQName; + OMNamespace namespace = factory.createOMNamespace(name.getNamespaceURI(), name.getPrefix()); + element.setNamespace(namespace); + element.setLocalName(name.getLocalPart()); + } + } + } + + public Class getTargetType() { + return OMElement.class; + } + + public Class getSourceType() { + return String.class; + } + + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/XMLStreamReader2OMElement.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/XMLStreamReader2OMElement.java new file mode 100755 index 0000000000..5b2c89b443 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/java/org/apache/tuscany/databinding/axiom/XMLStreamReader2OMElement.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.databinding.axiom; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.apache.tuscany.spi.model.DataType; +import org.osoa.sca.annotations.Service; + +@Service(Transformer.class) +public class XMLStreamReader2OMElement extends TransformerExtension<XMLStreamReader, OMElement> implements + PullTransformer<XMLStreamReader, OMElement> { + + public XMLStreamReader2OMElement() { + super(); + } + + public OMElement transform(XMLStreamReader source, TransformationContext context) { + try { + StAXOMBuilder builder = new StAXOMBuilder(source); + OMElement element = builder.getDocumentElement(); + adjustElementName(context, element); + return element; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + /** + * @param context + * @param element + */ + private void adjustElementName(TransformationContext context, OMElement element) { + if (context != null) { + DataType dataType = context.getTargetDataType(); + Object targetQName = dataType == null ? null : dataType.getLogical(); + if (!(targetQName instanceof QName)) { + return; + } + if (!element.getQName().equals(targetQName)) { + // TODO: Throw expection or switch to the new Element + OMFactory factory = OMAbstractFactory.getOMFactory(); + QName name = (QName)targetQName; + OMNamespace namespace = factory.createOMNamespace(name.getNamespaceURI(), name.getPrefix()); + element.setNamespace(namespace); + element.setLocalName(name.getLocalPart()); + } + } + } + + public Class getTargetType() { + return OMElement.class; + } + + public Class getSourceType() { + return XMLStreamReader.class; + } + + public int getWeight() { + return 10; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/resources/META-INF/sca/databinding.axiom.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/resources/META-INF/sca/databinding.axiom.scdl new file mode 100644 index 0000000000..0954b5a90f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/resources/META-INF/sca/databinding.axiom.scdl @@ -0,0 +1,57 @@ +<?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.
+-->
+<!-- This is the copy ot be included by other extensions --> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.axiom.include">
+
+ <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2">
+ <group>org.apache.tuscany.sca.services.databinding</group>
+ <name>databinding-axiom</name>
+ <version>1.0-incubator-M2-SNAPSHOT</version>
+ </dependency>
+
+ <component name="databinding.axiom">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.AxiomDataBinding" />
+ </component>
+
+ <component name="transformer.XMLStreamReader2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.XMLStreamReader2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2XMLStreamReader">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2XMLStreamReader" />
+ </component>
+
+ <component name="transformer.String2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.String2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2String">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2String" />
+ </component>
+
+ <component name="transformer.Object2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.Object2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2Object">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2Object" />
+ </component>
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..25e5a04c5c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,56 @@ +<?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.
+-->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.axiom">
+
+ <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2">
+ <group>org.apache.tuscany.sca.services.databinding</group>
+ <name>databinding-axiom</name>
+ <version>1.0-incubator-M2-SNAPSHOT</version>
+ </dependency>
+
+ <component name="databinding.axiom">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.AxiomDataBinding" />
+ </component>
+
+ <component name="transformer.XMLStreamReader2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.XMLStreamReader2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2XMLStreamReader">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2XMLStreamReader" />
+ </component>
+
+ <component name="transformer.String2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.String2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2String">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2String" />
+ </component>
+
+ <component name="transformer.Object2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.Object2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2Object">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2Object" />
+ </component>
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/java/org/apache/tuscany/databinding/axiom/OMElementTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/java/org/apache/tuscany/databinding/axiom/OMElementTestCase.java new file mode 100755 index 0000000000..5a2793225b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/java/org/apache/tuscany/databinding/axiom/OMElementTestCase.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.databinding.axiom; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.axiom.om.OMElement; + +public class OMElementTestCase 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>"; + + public final void testStringTransform() { + String2OMElement t1 = new String2OMElement(); + OMElement element = t1.transform(IPO_XML, null); + OMElement2String t2 = new OMElement2String(); + String xml = t2.transform(element, null); + Assert.assertNotNull(xml); + Assert.assertNotNull(xml.indexOf("<ipo:comment>") != -1); + } + + public final void testStAXTransform() { + String2OMElement t1 = new String2OMElement(); + OMElement element = t1.transform(IPO_XML, null); + + OMElement2XMLStreamReader t2 = new OMElement2XMLStreamReader(); + XMLStreamReader reader = t2.transform(element, null); + + XMLStreamReader2OMElement t3 = new XMLStreamReader2OMElement(); + OMElement element2 = t3.transform(reader, null); + + Assert.assertEquals(element2.getQName(), element.getQName()); + Assert.assertEquals(new QName("http://www.example.com/IPO", "purchaseOrder"), element2.getQName()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/resources/ipo.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/resources/ipo.xml new file mode 100755 index 0000000000..df901d183d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/resources/ipo.xml @@ -0,0 +1,51 @@ +<?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. +--> +<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> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/resources/ipo.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/resources/ipo.xsd new file mode 100755 index 0000000000..241ec15d36 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/resources/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-M2/sca/services/databinding/databinding-axiom/src/test/resources/order.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/resources/order.wsdl new file mode 100644 index 0000000000..7634cdebd3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-axiom/src/test/resources/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>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/LICENSE.txt new file mode 100755 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/pom.xml new file mode 100755 index 0000000000..9557263ea7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/pom.xml @@ -0,0 +1,114 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>databinding-castor</artifactId> + <name>Apache Tuscany Data Binding for Castor</name> + <description>Tuscany Castor Data Binding</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>castor</groupId> + <artifactId>castor</artifactId> + <version>1.0</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <version>1.0.4</version> + <scope>runtime</scope> + </dependency> + + <!-- Adding Apache xerces to workaround the castor references for SAX parser --> + <dependency> + <groupId>xerces</groupId> + <artifactId>xercesImpl</artifactId> + <version>2.8.0</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>1.0</version> + <executions> + <execution> + <id>add-test-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-test-source</goal> + </goals> + <configuration> + <sources> + <source>target/castor-source</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>generate-castor</id> + <phase>generate-test-sources</phase> + <configuration> + <tasks> + <taskdef name="castor-srcgen" + classname="org.exolab.castor.tools.ant.taskdefs.CastorSourceGenTask" + classpathref="maven.test.classpath" /> + <mkdir dir="${project.build.directory}/castor-source"></mkdir> + <castor-srcgen file="${basedir}/src/test/resources/ipo.xsd" + todir="${project.build.directory}/castor-source" package="com.example.ipo.castor" + types="j2" warnings="false" bindingfile="${basedir}/src/test/resources/binding.xml" /> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2Node.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2Node.java new file mode 100755 index 0000000000..9ae0335ada --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2Node.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.databinding.castor; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.extension.DOMHelper; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.exolab.castor.xml.Marshaller; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +public class Castor2Node<T> extends TransformerExtension<T, Node> implements PullTransformer<T, Node> { + private Class<T> type; + + public Castor2Node(Class<T> type) { + super(); + this.type = type; + } + + public Class getTargetType() { + return Node.class; + } + + public Class getSourceType() { + return type; + } + + public int getWeight() { + return 40; + } + + /** + * @see org.apache.tuscany.spi.databinding.PullTransformer#transform(java.lang.Object, org.apache.tuscany.spi.databinding.TransformationContext) + */ + public Node transform(Object source, TransformationContext context) { + try { + Document document = DOMHelper.newDocument(); + Marshaller.marshal(source, document); + return document; + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2SAX.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2SAX.java new file mode 100644 index 0000000000..643d6fb4ad --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2SAX.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.databinding.castor; + +import java.io.Writer; + +import org.apache.tuscany.spi.databinding.PushTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.exolab.castor.xml.Marshaller; + +public class Castor2SAX<T> extends TransformerExtension<T, Writer> implements PushTransformer<T, Writer> { + private Class<T> type; + + /** + * @param type + */ + public Castor2SAX(Class<T> type) { + super(); + this.type = type; + } + + public Class getSourceType() { + return type; + } + + public Class getTargetType() { + return Writer.class; + } + + public int getWeight() { + return 40; + } + + /** + * @see org.apache.tuscany.spi.databinding.PullTransformer#transform(java.lang.Object, org.apache.tuscany.spi.databinding.TransformationContext) + */ + public void transform(T source, Writer writer, TransformationContext context) { + try { + Marshaller.marshal(source, writer); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2Writer.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2Writer.java new file mode 100644 index 0000000000..f477273387 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Castor2Writer.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.databinding.castor; + +import org.apache.tuscany.spi.databinding.PushTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.exolab.castor.xml.Marshaller; +import org.xml.sax.ContentHandler; + +public class Castor2Writer<T> extends TransformerExtension<T, ContentHandler> implements PushTransformer<T, ContentHandler> { + private Class<T> type; + + /** + * @param type + */ + public Castor2Writer(Class<T> type) { + super(); + this.type = type; + } + + public Class getSourceType() { + return type; + } + + public Class getTargetType() { + return ContentHandler.class; + } + + public int getWeight() { + return 40; + } + + /** + * @see org.apache.tuscany.spi.databinding.PullTransformer#transform(java.lang.Object, org.apache.tuscany.spi.databinding.TransformationContext) + */ + public void transform(T source, ContentHandler contentHandler, TransformationContext context) { + try { + Marshaller.marshal(source, contentHandler); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/InputSource2Castor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/InputSource2Castor.java new file mode 100644 index 0000000000..61bac7d20f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/InputSource2Castor.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.databinding.castor; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.exolab.castor.xml.Unmarshaller; +import org.xml.sax.InputSource; + +public class InputSource2Castor<T> extends TransformerExtension<InputSource, T> implements PullTransformer<InputSource, T> { + private Class<T> type; + + /** + * @param type + */ + public InputSource2Castor(Class<T> type) { + super(); + this.type = type; + } + + public Class getTargetType() { + return type; + } + + public Class getSourceType() { + return InputSource.class; + } + + public int getWeight() { + return 40; + } + + /** + * @see org.apache.tuscany.spi.databinding.PullTransformer#transform(java.lang.Object, org.apache.tuscany.spi.databinding.TransformationContext) + */ + public T transform(InputSource source, TransformationContext context) { + try { + Object object = Unmarshaller.unmarshal(type, source); + return type.cast(object); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Node2Castor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Node2Castor.java new file mode 100644 index 0000000000..fa5a15b3ba --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Node2Castor.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.databinding.castor; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.exolab.castor.xml.Unmarshaller; +import org.w3c.dom.Node; + +public class Node2Castor<T> extends TransformerExtension<Node, T> implements PullTransformer<Node, T> { + private Class<T> type; + + /** + * @param type + */ + public Node2Castor(Class<T> type) { + super(); + this.type = type; + } + + public Class getTargetType() { + return type; + } + + public Class getSourceType() { + return Node.class; + } + + public int getWeight() { + return 40; + } + + /** + * @see org.apache.tuscany.spi.databinding.PullTransformer#transform(java.lang.Object, org.apache.tuscany.spi.databinding.TransformationContext) + */ + public T transform(Node source, TransformationContext context) { + try { + Object object = Unmarshaller.unmarshal(type, source); + return type.cast(object); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Reader2Castor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Reader2Castor.java new file mode 100644 index 0000000000..a8ade1bda5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/main/java/org/apache/tuscany/databinding/castor/Reader2Castor.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.castor; + +import java.io.Reader; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.exolab.castor.xml.Unmarshaller; + +public class Reader2Castor<T> extends TransformerExtension<Reader, T> implements PullTransformer<Reader, T> { + private Class<T> type; + + /** + * @param type + */ + public Reader2Castor(Class<T> type) { + super(); + this.type = type; + } + + public Class getTargetType() { + return type; + } + + public Class getSourceType() { + return Reader.class; + } + + public int getWeight() { + return 40; + } + + /** + * @see org.apache.tuscany.spi.databinding.PullTransformer#transform(java.lang.Object, org.apache.tuscany.spi.databinding.TransformationContext) + */ + public T transform(Reader source, TransformationContext context) { + try { + Object object = Unmarshaller.unmarshal(type, source); + return type.cast(object); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/java/org/apache/tuscany/databinding/castor/Castor2NodeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/java/org/apache/tuscany/databinding/castor/Castor2NodeTestCase.java new file mode 100644 index 0000000000..378e89866a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/java/org/apache/tuscany/databinding/castor/Castor2NodeTestCase.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.castor; + +import junit.framework.TestCase; + +public class Castor2NodeTestCase 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>"; + + public void testTransform() throws Exception { + // FIXME: There's a bug in the castor-generated code which cannot handle subutype correctly + // http://jira.codehaus.org/browse/CASTOR-1475 + // shipTo should be able to accept UKAddress +// Reader2Castor<PurchaseOrder> t1 = new Reader2Castor<PurchaseOrder>(PurchaseOrder.class); +// PurchaseOrder po = t1.transform(new StringReader(IPO_XML), null); + /* + * Castor2Node t2 = new Castor2Node(); Node node = t2.transform(po, null); Assert.assertNotNull(node); + */ + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/resources/binding.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/resources/binding.xml new file mode 100755 index 0000000000..3517e71692 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/resources/binding.xml @@ -0,0 +1,27 @@ +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<binding xmlns="http://www.castor.org/SourceGenerator/Binding" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + defaultBinding="type"> + + <elementBinding name="complexType:PurchaseOrderType/items"> + <java-class name="ItemsElement"/> + </elementBinding> + +</binding> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/resources/ipo.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/resources/ipo.xsd new file mode 100755 index 0000000000..241ec15d36 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/resources/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-M2/sca/services/databinding/databinding-castor/src/test/resources/org/exolab/castor/builder/castorbuilder.properties b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/resources/org/exolab/castor/builder/castorbuilder.properties new file mode 100644 index 0000000000..3f9f2eabb7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-castor/src/test/resources/org/exolab/castor/builder/castorbuilder.properties @@ -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. +# +# +# Property file for SourceCodeGenerator +# +# $Id: castorbuilder.properties,v 1.3 2004/05/06 08:20:51 kvisco Exp $ + +# To enable bound properties uncomment the following line. Please +# note that currently *all* fields will be treated as bound properties +# when enabled. This will change in the future when we introduce +# fine grained control over each class and it's properties. +# +#org.exolab.castor.builder.boundproperties=true + +# Java class mapping of <xsd:element>'s and <xsd:complexType>'s +# +org.exolab.castor.builder.javaclassmapping=type + +# This property allows one to specify the super class of *all* +# generated classes +# +#org.exolab.castor.builder.superclass=com.xyz.BaseObject + +# XML namespace mapping to Java packages +# +#org.exolab.castor.builder.nspackages=\ + http://www.xyz.com/schemas/project=com.xyz.schemas.project,\ + http://www.xyz.com/schemas/person=com.xyz.schemas.person + +# Set to true if you want to generate the equals method +# for each generated class +# false by default +# +#org.exolab.castor.builder.equalsmethod=true + +# Set to true if you want to use Object Wrappers instead +# of primitives (e.g Float instead of float). +# false by default. +# +#org.exolab.castor.builder.primitivetowrapper=false + +# Set to true if you want the generated class descriptors to +# expose the element and attribute names they contain. +# false by default. +# +#org.exolab.castor.builder.classdescfieldnames=false + +# Set to true if you want the generated source code to contain +# Extra methods for the collection fields, such as get/set using +# the collection type in addition to the type-safe array. +# Set this to true if you want your code to be more compatible +# with Castor JDO. This is false by default. +# +#org.exolab.castor.builder.extraCollectionMethods=true + +# Use old-style (Castor 0.9.3.9) of naming that uppercases +# names after an underscore +# +#org.exolab.castor.xml.JavaNaming.upperCaseAfterUnderscore=true + +# This property specifies whether generated enumerated type +# classes implement the EnumeratedTypeAccess interface. +# false by default +#org.exolab.castor.builder.enumTypeAccessInterface=true + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/LICENSE.txt new file mode 100755 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/pom.xml new file mode 100755 index 0000000000..8a76364cca --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/pom.xml @@ -0,0 +1,133 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>databinding-jaxb</artifactId> + <name>Apache Tuscany Data Binding for JAXB</name> + <description>Tuscany JAXB Data Binding</description> + + <repositories> + <repository> + <snapshots> + <enabled>true</enabled> + </snapshots> + <id>java.net</id> + <name>java.net Maven 1.x Repository</name> + <url>https://maven-repository.dev.java.net/nonav/repository</url> + <layout>legacy</layout> + </repository> + </repositories> + <pluginRepositories> + <pluginRepository> + <snapshots> + <enabled>true</enabled> + </snapshots> + <id>java.net</id> + <name>java.net Maven 1.x Repository</name> + <url>https://maven-repository.dev.java.net/repository</url> + <layout>legacy</layout> + </pluginRepository> + </pluginRepositories> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <version>2.0</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <version>2.0.2</version> + <scope>test</scope> + </dependency> + </dependencies> + + <build> + + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>1.0</version> + <executions> + <execution> + <id>add-test-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-test-source</goal> + </goals> + <configuration> + <sources> + <source>target/jaxb-source</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>com.sun.tools.xjc.maven2</groupId> + <artifactId>maven-jaxb-plugin</artifactId> + <version>1.0</version> + <executions> + <execution> + <id>generate-jaxb</id> + <phase>generate-test-sources</phase> + <goals> + <goal>generate</goal> + </goals> + </execution> + </executions> + <configuration> + <generatePackage>com.example.ipo.jaxb</generatePackage> + <generateDirectory>${project.build.directory}/jaxb-source</generateDirectory> + <schemaDirectory>${basedir}/src/test/resources</schemaDirectory> + <includeSchemas> + <includeSchema>ipo.xsd</includeSchema> + </includeSchemas> + </configuration> + </plugin> + + </plugins> + </build> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXB2Node.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXB2Node.java new file mode 100755 index 0000000000..90855b41b1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXB2Node.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.jaxb; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.DOMHelper; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +@Service(Transformer.class) +public class JAXB2Node extends TransformerExtension<Object, Node> implements PullTransformer<Object, Node> { + + public JAXB2Node() { + super(); + } + + public Node transform(Object source, TransformationContext tContext) { + if (source == null) + return null; + try { + JAXBContext context = JAXBContextHelper.createJAXBContext(tContext, true); + Marshaller marshaller = context.createMarshaller(); + // FIXME: The default Marshaller doesn't support + // marshaller.getNode() + Document document = DOMHelper.newDocument(); + marshaller.marshal(source, document); + return document; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return Object.class; + } + + public Class getTargetType() { + return Node.class; + } + + public int getWeight() { + return 30; + } + + @Override + public String getSourceDataBinding() { + return JAXBDataBinding.NAME; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBContextHelper.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBContextHelper.java new file mode 100644 index 0000000000..6f606dd757 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBContextHelper.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.databinding.jaxb; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; + +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.model.DataType; + +public class JAXBContextHelper { + // TODO: Do we need to set them for source and target? + public static final String JAXB_CLASSES = "jaxb.classes"; + + public static final String JAXB_CONTEXT_PATH = "jaxb.contextPath"; + + private JAXBContextHelper() { + } + + public static JAXBContext createJAXBContext(TransformationContext tContext, boolean source) throws JAXBException { + if (tContext == null) + throw new TransformationException("JAXB context is not set for the transformation."); + + // FIXME: We should check the context path or classes + // FIXME: What should we do if JAXB is an intermediate node? + DataType<?> bindingContext = source ? tContext.getSourceDataType() : tContext.getTargetDataType(); + String contextPath = (String) bindingContext.getMetadata(JAXB_CONTEXT_PATH); + JAXBContext context = null; + if (contextPath != null) + context = JAXBContext.newInstance(contextPath); + else { + Class[] classes = (Class[]) bindingContext.getMetadata(JAXB_CLASSES); + context = JAXBContext.newInstance(classes); + } + if (context == null) + throw new TransformationException("JAXB context is not set for the transformation."); + return context; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBDataBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBDataBinding.java new file mode 100644 index 0000000000..c43e9bcd42 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBDataBinding.java @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.databinding.jaxb; + +import java.beans.Introspector; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchema; +import javax.xml.bind.annotation.XmlType; +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.databinding.extension.DataBindingExtension; +import org.apache.tuscany.spi.model.DataType; + +/** + * JAXB DataBinding + */ +public class JAXBDataBinding extends DataBindingExtension { + + public static final String NAME = JAXBElement.class.getName(); + + @Override + public DataType introspect(Class<?> javaType) { + if (JAXBElement.class.isAssignableFrom(javaType)) { + Type type = javaType.getGenericSuperclass(); + if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = ((ParameterizedType) type); + Type rawType = parameterizedType.getRawType(); + if (rawType == JAXBElement.class) { + Type actualType = parameterizedType.getActualTypeArguments()[0]; + if (actualType instanceof Class) { + return introspect((Class<?>) actualType); + } + } + } + return new DataType<QName>(getName(), javaType, null); + } + + String namespace = null; + String name = null; + Package pkg = javaType.getPackage(); + if (pkg != null) { + XmlSchema schema = pkg.getAnnotation(XmlSchema.class); + namespace = schema.namespace(); + } + XmlType type = javaType.getAnnotation(XmlType.class); + if (type != null) { + String typeNamespace = type.namespace(); + String typeName = type.name(); + + if (typeNamespace.equals("##default") && typeName.equals("")) { + XmlRootElement rootElement = javaType.getAnnotation(XmlRootElement.class); + if (rootElement != null) { + namespace = rootElement.namespace(); + } else { + // FIXME: The namespace should be from the referencing property + namespace = null; + } + } else if (typeNamespace.equals("##default")) { + // namespace is from the package + } else { + namespace = typeNamespace; + } + + if (typeName.equals("##default")) { + name = Introspector.decapitalize(javaType.getSimpleName()); + } else { + name = typeName; + } + } else { + XmlEnum xmlEnum = javaType.getAnnotation(XmlEnum.class); + if (xmlEnum != null) { + name = Introspector.decapitalize(javaType.getSimpleName()); + } + } + if (namespace == null && name == null) { + return null; + } + QName xmlType = new QName(namespace, name); + DataType<QName> dataType = new DataType<QName>(getName(), javaType, xmlType); + return dataType; + } + + public JAXBDataBinding() { + super(NAME, JAXBElement.class); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBWrapperHandler.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBWrapperHandler.java new file mode 100644 index 0000000000..507f36eb19 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/JAXBWrapperHandler.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.databinding.jaxb; + +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlElementDecl; +import javax.xml.bind.annotation.XmlRegistry; +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.WrapperHandler; +import org.apache.tuscany.spi.idl.ElementInfo; + +/** + * JAXB WrapperHandler implementation + */ +public class JAXBWrapperHandler implements WrapperHandler<JAXBElement<?>> { + + public JAXBElement<?> create(ElementInfo element, TransformationContext context) { + try { + String packageName = null; + String factoryClassName = packageName + ".ObjectFactory"; + Class<?> factoryClass = Class.forName(factoryClassName, true, context.getClassLoader()); + assert factoryClass.isAnnotationPresent(XmlRegistry.class); + Object factory = factoryClass.newInstance(); + QName elementName = element.getQName(); + Method method = null; + for (Method m : factoryClass.getMethods()) { + XmlElementDecl xmlElement = m.getAnnotation(XmlElementDecl.class); + QName name = new QName(xmlElement.namespace(), xmlElement.name()); + if (xmlElement != null && name.equals(elementName)) { + method = m; + break; + } + } + if (method != null) { + Class typeClass = method.getParameterTypes()[0]; + Object value = typeClass.newInstance(); + return (JAXBElement<?>) method.invoke(factory, new Object[] { value }); + } else { + throw new TransformationException("ObjectFactory cannot be resolved."); + } + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Object getChild(JAXBElement<?> wrapper, int i, ElementInfo element) { + try { + Object value = wrapper.getValue(); + PropertyDescriptor descriptors[] = + Introspector.getBeanInfo(wrapper.getDeclaredType()).getPropertyDescriptors(); + for (PropertyDescriptor d : descriptors) { + if (d.getName().equals(element.getQName().getLocalPart())) { + return d.getReadMethod().invoke(value, new Object[] {}); + } + } + return null; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public void setChild(JAXBElement<?> wrapper, int i, ElementInfo childElement, Object value) { + try { + Object wrapperValue = wrapper.getValue(); + PropertyDescriptor descriptors[] = + Introspector.getBeanInfo(wrapper.getDeclaredType()).getPropertyDescriptors(); + for (PropertyDescriptor d : descriptors) { + if (d.getName().equals(childElement.getQName().getLocalPart())) { + d.getWriteMethod().invoke(wrapperValue, new Object[] { value }); + break; + } + } + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/Node2JAXB.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/Node2JAXB.java new file mode 100755 index 0000000000..ddb81c2eae --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/Node2JAXB.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.databinding.jaxb; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; +import org.w3c.dom.Node; + +@Service(Transformer.class) +public class Node2JAXB extends TransformerExtension<Node, Object> implements PullTransformer<Node, Object> { + + public Node2JAXB() { + super(); + } + + public Object transform(Node source, TransformationContext context) { + if (source == null) + return null; + try { + JAXBContext jaxbContext = JAXBContextHelper.createJAXBContext(context, false); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + return unmarshaller.unmarshal(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return Node.class; + } + + public Class getTargetType() { + return Object.class; + } + + public int getWeight() { + return 30; + } + + @Override + public String getTargetDataBinding() { + return JAXBDataBinding.NAME; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/Reader2JAXB.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/Reader2JAXB.java new file mode 100644 index 0000000000..36e05dd953 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/Reader2JAXB.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.jaxb; + +import java.io.Reader; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +@Service(Transformer.class) +public class Reader2JAXB extends TransformerExtension<Reader, Object> implements + PullTransformer<Reader, Object> { + + public Reader2JAXB() { + super(); + } + + public Object transform(Reader source, TransformationContext context) { + if (source == null) + return null; + try { + JAXBContext jaxbContext = JAXBContextHelper.createJAXBContext(context, false); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + StreamSource streamSource = new StreamSource(source); + return unmarshaller.unmarshal(streamSource); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return Reader.class; + } + + public Class getTargetType() { + return Object.class; + } + + public int getWeight() { + return 30; + } + + @Override + public String getTargetDataBinding() { + return JAXBDataBinding.NAME; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/XMLStreamReader2JAXB.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/XMLStreamReader2JAXB.java new file mode 100755 index 0000000000..23d2586613 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/java/org/apache/tuscany/databinding/jaxb/XMLStreamReader2JAXB.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.databinding.jaxb; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +@Service(Transformer.class) +public class XMLStreamReader2JAXB extends TransformerExtension<XMLStreamReader, Object> implements + PullTransformer<XMLStreamReader, Object> { + + public XMLStreamReader2JAXB() { + super(); + } + + public Object transform(XMLStreamReader source, TransformationContext context) { + if (source == null) + return null; + try { + JAXBContext jaxbContext = JAXBContextHelper.createJAXBContext(context, false); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + return unmarshaller.unmarshal(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return XMLStreamReader.class; + } + + public Class getTargetType() { + return Object.class; + } + + public int getWeight() { + return 10; + } + + @Override + public String getTargetDataBinding() { + return JAXBDataBinding.NAME; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..2b86e506eb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,43 @@ +<?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.
+--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.JAXB">
+
+ <component name="databinding.jaxb">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.JAXBDataBinding" />
+ </component>
+
+ <component name="transformer.XMLStreamReader2JAXB">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.XMLStreamReader2JAXB" />
+ </component>
+
+ <component name="transformer.Node2JAXB">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.Node2JAXB" />
+ </component>
+
+ <component name="transformer.JAXB2Node">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.JAXB2Node" />
+ </component>
+
+ <component name="transformer.Reader2JAXB">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.Reader2JAXB" />
+ </component>
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/java/org/apache/tuscany/databinding/jaxb/JAXBDataBindingTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/java/org/apache/tuscany/databinding/jaxb/JAXBDataBindingTestCase.java new file mode 100644 index 0000000000..1b80be724f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/java/org/apache/tuscany/databinding/jaxb/JAXBDataBindingTestCase.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.databinding.jaxb; + +import javax.xml.bind.JAXBElement; +import javax.xml.namespace.QName; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.spi.model.DataType; + +import com.example.ipo.jaxb.PurchaseOrderType; +import com.example.ipo.jaxb.USAddress; +import com.example.ipo.jaxb.USState; + +/** + * + */ +public class JAXBDataBindingTestCase extends TestCase { + private JAXBDataBinding binding; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + binding = new JAXBDataBinding(); + } + + /** + * Test method for {@link org.apache.tuscany.databinding.jaxb.JAXBDataBinding#introspect(java.lang.Class)}. + */ + public final void testIntrospect() { + DataType<?> dataType = binding.introspect(JAXBElement.class); + Assert.assertTrue(dataType.getDataBinding().equals(binding.getName())); + Assert.assertTrue(dataType.getPhysical() == JAXBElement.class && dataType.getLogical() == null); + dataType = binding.introspect(MockJAXBElement.class); + Assert.assertEquals(PurchaseOrderType.class, dataType.getPhysical()); + Assert.assertEquals(new QName("http://www.example.com/IPO", "PurchaseOrderType"), dataType.getLogical()); + dataType = binding.introspect(USAddress.class); + Assert.assertEquals(USAddress.class, dataType.getPhysical()); + Assert.assertEquals(new QName("http://www.example.com/IPO", "USAddress"), dataType.getLogical()); + dataType = binding.introspect(USState.class); + Assert.assertTrue(dataType.getDataBinding().equals(binding.getName())); + Assert.assertEquals(USState.class, dataType.getPhysical()); + Assert.assertEquals(new QName("http://www.example.com/IPO", "USState"), dataType.getLogical()); + + } + + private static class MockJAXBElement extends JAXBElement<PurchaseOrderType> { + + private static final long serialVersionUID = -2767569071002707973L; + + /** + * @param elementName + * @param type + * @param value + */ + public MockJAXBElement(QName elementName, Class<PurchaseOrderType> type, PurchaseOrderType value) { + super(elementName, type, value); + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/java/org/apache/tuscany/databinding/jaxb/JAXBTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/java/org/apache/tuscany/databinding/jaxb/JAXBTestCase.java new file mode 100755 index 0000000000..ebc537805e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/java/org/apache/tuscany/databinding/jaxb/JAXBTestCase.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.databinding.jaxb; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +import java.io.StringReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.model.DataType; +import org.w3c.dom.Node; + +public class JAXBTestCase 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 String contextPath = "com.example.ipo.jaxb"; + + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransform() throws Exception { + Reader2JAXB t0 = new Reader2JAXB(); + + DataType targetDataType = new DataType<Class>(Object.class, null); + targetDataType.setMetadata(JAXBContextHelper.JAXB_CONTEXT_PATH, contextPath); + + TransformationContext tContext = createMock(TransformationContext.class); + expect(tContext.getTargetDataType()).andReturn(targetDataType).anyTimes(); + replay(tContext); + + Object object1 = t0.transform(new StringReader(IPO_XML), tContext); + + DataType sourceDataType = new DataType<Class>(Object.class, null); + sourceDataType.setMetadata(JAXBContextHelper.JAXB_CONTEXT_PATH, contextPath); + + TransformationContext tContext1 = createMock(TransformationContext.class); + expect(tContext1.getSourceDataType()).andReturn(sourceDataType).anyTimes(); + replay(tContext1); + + JAXB2Node t1 = new JAXB2Node(); + Node node = t1.transform(object1, tContext1); + + Assert.assertNotNull(node); + + Node2JAXB t2 = new Node2JAXB(); + Object object2 = t2.transform(node, tContext); + Assert.assertNotNull(object2); + + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/resources/ipo.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/resources/ipo.xsd new file mode 100755 index 0000000000..241ec15d36 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-jaxb/src/test/resources/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-M2/sca/services/databinding/databinding-sdo/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/LICENSE.txt new file mode 100755 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/pom.xml new file mode 100755 index 0000000000..a7091dcc90 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/pom.xml @@ -0,0 +1,119 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>databinding-sdo</artifactId> + <name>Apache Tuscany Data Binding for SDO</name> + <description>Data Binding based on SDO.</description> + + <!-- include incubator repo as a plugin repo --> + <pluginRepositories> + <pluginRepository> + <id>apache.incubator</id> + <name>Apache Incubator Repository</name> + <url>http://people.apache.org/repo/m2-incubating-repository/</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> + </pluginRepositories> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sdo</groupId> + <artifactId>tuscany-sdo-impl</artifactId> + <version>1.0-incubator-M2</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>core</artifactId> + <version>${pom.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>1.0</version> + <executions> + <execution> + <id>add-test-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-test-source</goal> + </goals> + <configuration> + <sources> + <source>target/sdo-source</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.tuscany.sdo</groupId> + <artifactId>tuscany-sdo-plugin</artifactId> + <version>1.0-incubator-M2</version> + <executions> + <execution> + <id>generate-sdo</id> + <phase>generate-test-sources</phase> + <configuration> + <schemaFile>${basedir}/src/test/resources/ipo.xsd</schemaFile> + <javaPackage>com.example.ipo.sdo</javaPackage> + <noNotification>true</noNotification> + <noContainer>true</noContainer> + <noUnsettable>true</noUnsettable> + </configuration> + <goals> + <goal>generate</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObject2String.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObject2String.java new file mode 100755 index 0000000000..bae01a69b2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObject2String.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.databinding.sdo; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLHelper; + +@Service(Transformer.class) +public class DataObject2String extends TransformerExtension<DataObject, String> implements + PullTransformer<DataObject, String> { + + private static final String TUSCANY_SDO = "http://incubator.apache.org/tuscany/xmlns/sdo/1.0-incubator-M2"; + + public String transform(DataObject source, TransformationContext context) { + try { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + XMLHelper xmlHelper = SDOUtil.createXMLHelper(typeHelper); + Object logicalType = context.getSourceDataType().getLogical(); + if (logicalType instanceof QName) { + QName elementName = (QName) logicalType; + return xmlHelper.save(source, elementName.getNamespaceURI(), elementName.getLocalPart()); + } else { + return xmlHelper.save(source, TUSCANY_SDO, "dataObject"); + } + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return DataObject.class; + } + + public Class getTargetType() { + return String.class; + } + + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObject2XMLStreamReader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObject2XMLStreamReader.java new file mode 100755 index 0000000000..8caba8458d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObject2XMLStreamReader.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.sdo; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sdo.helper.XMLStreamHelper; +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +@Service(Transformer.class) +public class DataObject2XMLStreamReader extends TransformerExtension<DataObject, XMLStreamReader> implements + PullTransformer<DataObject, XMLStreamReader> { + + public XMLStreamReader transform(DataObject source, TransformationContext context) { + try { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(typeHelper); + Object logicalType = context.getSourceDataType().getLogical(); + QName elementName = + (logicalType instanceof QName) ? (QName) logicalType : new QName("commonj.sdo", "dataObject"); + XMLHelper xmlHelper = SDOUtil.createXMLHelper(typeHelper); + XMLDocument document = + xmlHelper.createDocument(source, elementName.getNamespaceURI(), elementName.getLocalPart()); + return streamHelper.createXMLStreamReader(document); + } catch (XMLStreamException e) { + // TODO: Add context to the exception + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return DataObject.class; + } + + public Class getTargetType() { + return XMLStreamReader.class; + } + + public int getWeight() { + return 10; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObjectLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObjectLoader.java new file mode 100755 index 0000000000..cd45575004 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/DataObjectLoader.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.databinding.sdo; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sdo.helper.XMLStreamHelper; +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.StAXElementLoader; +import org.apache.tuscany.spi.model.ModelObject; +import org.apache.tuscany.spi.annotation.Autowire; + +import commonj.sdo.DataObject; +import commonj.sdo.Property; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XSDHelper; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Destroy; + +/** + * A SDO model-based Loader to load DataObject from the XML stream + * + */ +public class DataObjectLoader implements StAXElementLoader<ModelObject> { + protected LoaderRegistry registry; + private QName propertyQName; + + public DataObjectLoader(Property property) { + super(); + this.propertyQName = new QName(XSDHelper.INSTANCE.getNamespaceURI(property), + XSDHelper.INSTANCE.getLocalName(property)); + } + + public DataObjectLoader(QName propertyQName) { + super(); + this.propertyQName = propertyQName; + } + + public ModelObject load(CompositeComponent parent, XMLStreamReader reader, DeploymentContext deploymentContext) throws XMLStreamException, LoaderException { + assert propertyQName.equals(reader.getName()); + // TODO: We need a way to get TypeHelper from deploymentContext + TypeHelper typeHelper = TypeHelper.INSTANCE; + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(typeHelper); + DataObject dataObject = streamHelper.loadObject(reader); + // TODO: Is it required that the object always extends from ModelObject? + return new ModelDataObject(dataObject); + } + + @Autowire + public void setRegistry(LoaderRegistry registry) { + this.registry = registry; + } + + @Init(eager = true) + public void start() { + registry.registerLoader(propertyQName, this); + } + + @Destroy + public void stop() { + registry.unregisterLoader(propertyQName, this); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/ImportSDOLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/ImportSDOLoader.java new file mode 100755 index 0000000000..ac8ca776c9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/ImportSDOLoader.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.sdo; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; +import org.apache.tuscany.spi.model.ModelObject; +import org.osoa.sca.annotations.Constructor; + +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XSDHelper; + +/** + * Loader that handles <import.sdo> elements. + * + * @version $Rev$ $Date$ + */ +public class ImportSDOLoader extends LoaderExtension { + public static final QName IMPORT_SDO = + new QName("http://incubator.apache.org/tuscany/xmlns/databinding/sdo/1.0-incubator-M2", "import.sdo"); + + @Constructor( { "registry" }) + public ImportSDOLoader(@Autowire LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return IMPORT_SDO; + } + + public ModelObject load(CompositeComponent parent, XMLStreamReader reader, DeploymentContext deploymentContext) + throws XMLStreamException, LoaderException { + assert IMPORT_SDO.equals(reader.getName()); + + // FIXME: [rfeng] How to associate the TypeHelper with deployment context? + TypeHelper typeHelper = TypeHelper.INSTANCE; + if (deploymentContext != null && deploymentContext.getParent() != null) { + typeHelper = (TypeHelper) deploymentContext.getParent().getExtension(TypeHelper.class.getName()); + if (typeHelper == null) { + typeHelper = SDOUtil.createTypeHelper(); + deploymentContext.getParent().putExtension(TypeHelper.class.getName(), typeHelper); + } + } + + importFactory(reader, deploymentContext); + importWSDL(reader, deploymentContext, typeHelper); + LoaderUtil.skipToEndElement(reader); + return new SDOType(typeHelper); + } + + private void importFactory(XMLStreamReader reader, DeploymentContext deploymentContext) throws LoaderException { + String factoryName = reader.getAttributeValue(null, "factory"); + if (factoryName != null) { + ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); + try { + // set TCCL as SDO needs it + ClassLoader cl = deploymentContext.getClassLoader(); + Thread.currentThread().setContextClassLoader(cl); + Class<?> factoryClass = cl.loadClass(factoryName); + // FIXME: We require the SDO to provide an API to register static types in a given TypeHelper + SDOUtil.registerStaticTypes(factoryClass); + } catch (ClassNotFoundException e) { + throw new LoaderException(e.getMessage(), e); + } finally { + Thread.currentThread().setContextClassLoader(oldCL); + } + } + } + + private void importWSDL(XMLStreamReader reader, DeploymentContext deploymentContext, TypeHelper typeHelper) + throws LoaderException { + String location = reader.getAttributeValue(null, "location"); + if (location == null) + location = reader.getAttributeValue(null, "wsdlLocation"); + if (location != null) { + try { + URL wsdlURL = null; + URI uri = URI.create(location); + if (uri.isAbsolute()) { + wsdlURL = uri.toURL(); + } + wsdlURL = deploymentContext.getClassLoader().getResource(location); + if (null == wsdlURL) { + LoaderException loaderException = new LoaderException("WSDL location error"); + loaderException.setResourceURI(location); + throw loaderException; + } + InputStream xsdInputStream = wsdlURL.openStream(); + try { + XSDHelper xsdHelper = SDOUtil.createXSDHelper(typeHelper); + xsdHelper.define(xsdInputStream, wsdlURL.toExternalForm()); + } finally { + xsdInputStream.close(); + } + } catch (IOException e) { + LoaderException sfe = new LoaderException(e.getMessage()); + sfe.setResourceURI(location); + throw sfe; + } + } + } + + public static class SDOType extends ModelObject { + private TypeHelper typeHelper; + + public SDOType(TypeHelper typeHelper) { + super(); + this.typeHelper = typeHelper; + } + + public TypeHelper getTypeHelper() { + return typeHelper; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/ModelDataObject.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/ModelDataObject.java new file mode 100755 index 0000000000..a3870b5e9a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/ModelDataObject.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.sdo; + +import org.apache.tuscany.spi.model.ModelObject; + +import commonj.sdo.DataObject; + +public class ModelDataObject extends ModelObject { + private DataObject dataObject; + + public ModelDataObject(DataObject dataObject) { + super(); + this.dataObject = dataObject; + } + + public DataObject getDataObject() { + return dataObject; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDODataBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDODataBinding.java new file mode 100644 index 0000000000..213dfd9280 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDODataBinding.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.databinding.sdo; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.databinding.WrapperHandler; +import org.apache.tuscany.spi.databinding.extension.DataBindingExtension; +import org.apache.tuscany.spi.model.DataType; + +import commonj.sdo.DataObject; +import commonj.sdo.Type; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XSDHelper; + +/** + * + */ +public class SDODataBinding extends DataBindingExtension { + private WrapperHandler<Object> wrapperHandler; + + @Override + public DataType introspect(Class<?> javaType) { + if (javaType == DataObject.class) { + return new DataType<QName>(getName(), javaType, null); + } + Type type = TypeHelper.INSTANCE.getType(javaType); + if (type == null || type.isDataType()) { + return null; + } + String namespace = type.getURI(); + String name = XSDHelper.INSTANCE.getLocalName(type); + QName xmlType = new QName(namespace, name); + DataType<QName> dataType = new DataType<QName>(getName(), javaType, xmlType); + return dataType; + } + + public SDODataBinding() { + super(DataObject.class); + wrapperHandler = new SDOWrapperHandler(); + } + + @Override + public WrapperHandler getWrapperHandler() { + return wrapperHandler; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDODataTypeHelper.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDODataTypeHelper.java new file mode 100644 index 0000000000..9d88c9fa58 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDODataTypeHelper.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.databinding.sdo; + +import org.apache.tuscany.databinding.sdo.ImportSDOLoader.SDOType; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.databinding.TransformationContext; + +import commonj.sdo.helper.TypeHelper; + +/** + * Helper class to get TypeHelper from the transformation context + */ +public class SDODataTypeHelper { + private SDODataTypeHelper() { + } + + public static TypeHelper getTypeHelper(TransformationContext context) { + TypeHelper typeHelper = null; + if (context == null || context.getMetadata() == null) { + return TypeHelper.INSTANCE; + } + CompositeComponent composite = (CompositeComponent) context.getMetadata().get(CompositeComponent.class); + if (composite != null) { + SDOType sdoType = (SDOType) composite.getExtensions().get(SDOType.class); + if (sdoType != null) { + typeHelper = sdoType.getTypeHelper(); + } + } + if (typeHelper == null) { + return TypeHelper.INSTANCE; + } + return typeHelper; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOObjectFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOObjectFactory.java new file mode 100755 index 0000000000..0c3e74cdc7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOObjectFactory.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.databinding.sdo; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.CopyHelper; +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.ObjectCreationException; + +/** + * Creates new instances of an SDO + * + * @version $Rev$ $Date$ + */ +public class SDOObjectFactory implements ObjectFactory<DataObject> { + + private DataObject dataObject; + + public SDOObjectFactory(DataObject dataObject) { + this.dataObject = dataObject; + } + + public DataObject getInstance() throws ObjectCreationException { + return CopyHelper.INSTANCE.copy(dataObject); + } + + public void releaseInstance(DataObject instance) { + } + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOSimpleTypeMapper.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOSimpleTypeMapper.java new file mode 100644 index 0000000000..78e2c4e0c2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOSimpleTypeMapper.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.databinding.sdo; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.SimpleTypeMapper; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.idl.TypeInfo; + +import commonj.sdo.Type; +import commonj.sdo.helper.TypeHelper; + +/** + * SDO Java/XML mapping for simple XSD types + */ +public class SDOSimpleTypeMapper implements SimpleTypeMapper { + public static final String URI_2001_SCHEMA_XSD = "http://www.w3.org/2001/XMLSchema"; + + public SDOSimpleTypeMapper() { + super(); + } + + public Object toJavaObject(TypeInfo simpleType, String value, TransformationContext context) { + QName typeName = simpleType.getQName(); + Type type = null; + if (URI_2001_SCHEMA_XSD.equals(typeName.getNamespaceURI())) { + type = SDOUtil.getXSDSDOType(typeName.getLocalPart()); + } else { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + type = typeHelper.getType(typeName.getNamespaceURI(), typeName.getLocalPart()); + } + return SDOUtil.createFromString(type, value); + } + + public String toXMLLiteral(TypeInfo simpleType, Object obj, TransformationContext context) { + QName typeName = simpleType.getQName(); + Type type = null; + if (URI_2001_SCHEMA_XSD.equals(typeName.getNamespaceURI())) { + type = SDOUtil.getXSDSDOType(typeName.getLocalPart()); + } else { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + if (typeHelper == null) { + typeHelper = TypeHelper.INSTANCE; + } + type = typeHelper.getType(typeName.getNamespaceURI(), typeName.getLocalPart()); + } + return SDOUtil.convertToString(type, obj); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOWrapperHandler.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOWrapperHandler.java new file mode 100644 index 0000000000..d34b389458 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/SDOWrapperHandler.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.databinding.sdo; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.WrapperHandler; +import org.apache.tuscany.spi.idl.ElementInfo; +import org.apache.tuscany.spi.model.DataType; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.DataFactory; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +/** + * SDO Wrapper Handler + */ +public class SDOWrapperHandler implements WrapperHandler<Object> { + + /** + * @see org.apache.tuscany.spi.databinding.WrapperHandler#create(ElementInfo, + * TransformationContext) + */ + public Object create(ElementInfo element, TransformationContext context) { + TypeHelper typeHelper = TypeHelper.INSTANCE; + if (context != null) { + DataType targetType = context.getTargetDataType(); + if (targetType != null) { + typeHelper = (TypeHelper) targetType.getMetadata(TypeHelper.class.getName()); + if (typeHelper == null) { + typeHelper = TypeHelper.INSTANCE; + } + } + } + QName typeName = element.getType().getQName(); + DataFactory dataFactory = SDOUtil.createDataFactory(typeHelper); + DataObject root = dataFactory.create(typeName.getNamespaceURI(), typeName.getLocalPart()); + XMLHelper xmlHelper = SDOUtil.createXMLHelper(typeHelper); + return xmlHelper.createDocument(root, element.getQName().getNamespaceURI(), element.getQName().getLocalPart()); + } + + /** + * @see org.apache.tuscany.spi.databinding.WrapperHandler#getChild(java.lang.Object, int, + * ElementInfo) + */ + public Object getChild(Object wrapper, int i, ElementInfo element) { + DataObject wrapperDO = + (wrapper instanceof XMLDocument) ? ((XMLDocument) wrapper).getRootObject() : (DataObject) wrapper; + return wrapperDO.get(element.getQName().getLocalPart()); + } + + /** + * @see org.apache.tuscany.spi.databinding.WrapperHandler#setChild(java.lang.Object, int, + * ElementInfo, java.lang.Object) + */ + public void setChild(Object wrapper, int i, ElementInfo childElement, Object value) { + DataObject wrapperDO = + (wrapper instanceof XMLDocument) ? ((XMLDocument) wrapper).getRootObject() : (DataObject) wrapper; + wrapperDO.set(childElement.getQName().getLocalPart(), value); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/String2DataObject.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/String2DataObject.java new file mode 100755 index 0000000000..81b0b7dbcc --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/String2DataObject.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.databinding.sdo; + +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLHelper; + +@Service(Transformer.class) +public class String2DataObject extends TransformerExtension<String, DataObject> implements PullTransformer<String, DataObject> { + + public DataObject transform(String source, TransformationContext context) { + try { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + XMLHelper xmlHelper = SDOUtil.createXMLHelper(typeHelper); + return xmlHelper.load(source).getRootObject(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return String.class; + } + + public Class getTargetType() { + return DataObject.class; + } + + public int getWeight() { + return 50; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLDocument2String.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLDocument2String.java new file mode 100644 index 0000000000..8870000838 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLDocument2String.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.databinding.sdo; + +import java.io.StringWriter; + +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +@Service(Transformer.class) +public class XMLDocument2String extends TransformerExtension<XMLDocument, String> implements + PullTransformer<XMLDocument, String> { + + public String transform(XMLDocument source, TransformationContext context) { + try { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + XMLHelper xmlHelper = SDOUtil.createXMLHelper(typeHelper); + StringWriter writer = new StringWriter(); + xmlHelper.save(source, writer, null); + return writer.toString(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return XMLDocument.class; + } + + public Class getTargetType() { + return String.class; + } + + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLDocument2XMLStreamReader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLDocument2XMLStreamReader.java new file mode 100755 index 0000000000..92563f37d2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLDocument2XMLStreamReader.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.databinding.sdo; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sdo.helper.XMLStreamHelper; +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLDocument; + +@Service(Transformer.class) +public class XMLDocument2XMLStreamReader extends TransformerExtension<XMLDocument, XMLStreamReader> implements PullTransformer<XMLDocument, XMLStreamReader> { + /** + * @param source + * @param context + * @return + */ + public XMLStreamReader transform(XMLDocument source, TransformationContext context) { + try { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(typeHelper); + return streamHelper.createXMLStreamReader(source); + } catch (XMLStreamException e) { + throw new TransformationException(e); + } + } + + public Class getSourceType() { + return XMLDocument.class; + } + + public Class getTargetType() { + return XMLStreamReader.class; + } + + public int getWeight() { + return 10; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLStreamReader2DataObject.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLStreamReader2DataObject.java new file mode 100755 index 0000000000..e00396820a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLStreamReader2DataObject.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.databinding.sdo; + +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sdo.helper.XMLStreamHelper; +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.TypeHelper; + +@Service(Transformer.class) +public class XMLStreamReader2DataObject extends TransformerExtension<XMLStreamReader, DataObject> implements + PullTransformer<XMLStreamReader, DataObject> { + + public DataObject transform(XMLStreamReader source, TransformationContext context) { + try { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(typeHelper); + // The XMLStreamHelper requires that the reader is posistioned at START_ELEMENT + while (source.getEventType() != XMLStreamConstants.START_ELEMENT && source.hasNext()) { + source.next(); + } + return streamHelper.loadObject(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getTargetType() { + return DataObject.class; + } + + public Class getSourceType() { + return XMLStreamReader.class; + } + + public int getWeight() { + return 15; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLStreamReader2XMLDocument.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLStreamReader2XMLDocument.java new file mode 100755 index 0000000000..063fbca812 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/java/org/apache/tuscany/databinding/sdo/XMLStreamReader2XMLDocument.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.databinding.sdo; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sdo.helper.XMLStreamHelper; +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.osoa.sca.annotations.Service; + +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLDocument; + +@Service(Transformer.class) +public class XMLStreamReader2XMLDocument extends TransformerExtension<XMLStreamReader, XMLDocument> implements + PullTransformer<XMLStreamReader, XMLDocument> { + + public XMLDocument transform(XMLStreamReader source, TransformationContext context) { + try { + TypeHelper typeHelper = SDODataTypeHelper.getTypeHelper(context); + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(typeHelper); + return streamHelper.load(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public Class getTargetType() { + return XMLDocument.class; + } + + public Class getSourceType() { + return XMLStreamReader.class; + } + + public int getWeight() { + return 15; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/resources/META-INF/sca/databinding.sdo.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/resources/META-INF/sca/databinding.sdo.scdl new file mode 100644 index 0000000000..245f06e1cd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/resources/META-INF/sca/databinding.sdo.scdl @@ -0,0 +1,68 @@ +<?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.
+-->
+<!--
+ SDO databinding extension
+
+ This is the copy to be included by other extensions
+
+ $Rev: 431086 $ $Date: 2006-08-12 13:58:17 -0700 (Sat, 12 Aug 2006) $
+-->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0"
+ xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.sdo.include">
+
+ <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2">
+ <group>org.apache.tuscany.sca.services.databinding</group>
+ <name>databinding-sdo</name>
+ <version>1.0-incubator-M2-SNAPSHOT</version>
+ </dependency>
+
+ <!-- import.sdo element loader implementations -->
+ <component name="elementLoader.import.sdo">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.ImportSDOLoader"/>
+ </component>
+
+ <component name="databinding.sdo">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.SDODataBinding" />
+ </component>
+
+ <component name="transformer.DataObject2String">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.DataObject2String"/>
+ </component>
+ <component name="transformer.DataObject2XMLStreamReader">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.DataObject2XMLStreamReader"/>
+ </component>
+ <component name="transformer.XMLDocument2String">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLDocument2String"/>
+ </component>
+ <component name="transformer.String2DataObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.String2DataObject"/>
+ </component>
+ <component name="transformer.XMLDocument2XMLStreamReader">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLDocument2XMLStreamReader"/>
+ </component>
+ <component name="transformer.XMLStreamReader2DataObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLStreamReader2DataObject"/>
+ </component>
+ <component name="transformer.XMLStreamReader2XMLDocument">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLStreamReader2XMLDocument"/>
+ </component>
+
+</composite>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..e554690be9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,66 @@ +<?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. +--> +<!-- + SDO databinding extension + + $Rev: 431086 $ $Date: 2006-08-12 13:58:17 -0700 (Sat, 12 Aug 2006) $ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + name="org.apache.tuscany.databinding.sdo"> + + <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2"> + <group>org.apache.tuscany.sca.services.databinding</group> + <name>databinding-sdo</name> + <version>1.0-incubator-M2-SNAPSHOT</version> + </dependency> + + <!-- import.sdo element loader implementations --> + <component name="elementLoader.import.sdo"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.ImportSDOLoader"/> + </component> + + <component name="databinding.sdo"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.SDODataBinding" /> + </component> + + <component name="transformer.DataObject2String"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.DataObject2String"/> + </component> + <component name="transformer.DataObject2XMLStreamReader"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.DataObject2XMLStreamReader"/> + </component> + <component name="transformer.XMLDocument2String"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLDocument2String"/> + </component> + <component name="transformer.String2DataObject"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.String2DataObject"/> + </component> + <component name="transformer.XMLDocument2XMLStreamReader"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLDocument2XMLStreamReader"/> + </component> + <component name="transformer.XMLStreamReader2DataObject"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLStreamReader2DataObject"/> + </component> + <component name="transformer.XMLStreamReader2XMLDocument"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLStreamReader2XMLDocument"/> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObject2StringTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObject2StringTestCase.java new file mode 100644 index 0000000000..28a885cd16 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObject2StringTestCase.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.databinding.sdo; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.apache.tuscany.spi.model.DataType; + +import com.example.ipo.sdo.PurchaseOrderType; +import commonj.sdo.DataObject; + +/** + * + */ +public class DataObject2StringTestCase extends SDOTransformerTestCaseBase { + @Override + protected DataType<?> getSourceDataType() { + return new DataType<QName>(binding, PurchaseOrderType.class, orderQName); + } + + @Override + protected DataType<?> getTargetDataType() { + return new DataType<Class<String>>(String.class, String.class); + } + + public final void testTransform() { + String xml = new DataObject2String().transform(dataObject, context); + Assert.assertTrue(xml.indexOf("<city>San Jose</city>") != -1); + DataObject po = new String2DataObject().transform(xml, reversedContext); + Assert.assertTrue(po instanceof PurchaseOrderType); + PurchaseOrderType orderType = (PurchaseOrderType) po; + Assert.assertEquals("San Jose", orderType.getBillTo().getCity()); + } + + public final void testXML() { + String xml = + "<foo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ipo=\"http://www.example.com/IPO\" xsi:type=\"ipo:USAddress\"/>"; + DataObject dataObject = new String2DataObject().transform(xml, reversedContext); + context.setSourceDataType(new DataType<QName>(DataObject.class.getName(), DataObject.class, null)); + xml = new DataObject2String().transform(dataObject, context); + Assert.assertTrue(xml.contains("xsi:type=\"ipo:USAddress\"")); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObject2XMLStreamReaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObject2XMLStreamReaderTestCase.java new file mode 100644 index 0000000000..5ab23c6df1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObject2XMLStreamReaderTestCase.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.databinding.sdo; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.model.DataType; + +import com.example.ipo.sdo.PurchaseOrderType; + +/** + * + */ +public class DataObject2XMLStreamReaderTestCase extends SDOTransformerTestCaseBase { + + @Override + protected DataType<?> getSourceDataType() { + return new DataType<QName>(binding, PurchaseOrderType.class, orderQName); + } + + @Override + protected DataType<?> getTargetDataType() { + return new DataType<Class<XMLStreamReader>>(XMLStreamReader.class, XMLStreamReader.class); + } + + public final void testTransform() throws XMLStreamException { + XMLStreamReader reader = new DataObject2XMLStreamReader().transform(dataObject, context); + while (reader.hasNext()) { + int event = reader.next(); + if (event == XMLStreamConstants.START_ELEMENT) + break; + } + new XMLStreamReader2DataObject().transform(reader, reversedContext); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObjectLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObjectLoaderTestCase.java new file mode 100755 index 0000000000..8cdbf0a295 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/DataObjectLoaderTestCase.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.sdo; + +import java.io.StringReader; +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.apache.tuscany.spi.deployer.DeploymentContext; + +import commonj.sdo.helper.XSDHelper; + +public class DataObjectLoaderTestCase extends TestCase { + + private XSDHelper xsdHelper = XSDHelper.INSTANCE; + + private QName name = new QName("http://www.osoa.org/xmlns/mock/0.9", "implementation.mock"); + + private String xml = "<module name=\"m\" xmlns=\"http://www.osoa.org/xmlns/sca/0.9\" xmlns:mock=\"http://www.osoa.org/xmlns/mock/0.9\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.osoa.org/xmlns/mock/0.9 sca-implementation-mock.xsd http://www.osoa.org/xmlns/sca/0.9 sca-core.xsd \"><component name=\"c\"><mock:implementation.mock myAttr=\"helloworld.HelloWorldImpl\" /></component></module>"; + + @Override + protected void setUp() throws Exception { + super.setUp(); + URL url = getClass().getClassLoader().getResource("model/sca-implementation-mock.xsd"); + // URL url = getClass().getClassLoader().getResource("model/sca-core.xsd"); + xsdHelper.define(url.openStream(), url.toExternalForm()); + } + + public void testLoader() throws Exception { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(xml)); + int event = reader.getEventType(); + while (!(event == XMLStreamConstants.START_ELEMENT && reader.getName().equals(name)) && reader.hasNext()) { + event = reader.nextTag(); + } + DataObjectLoader loader = new DataObjectLoader(name); + DeploymentContext context = new RootDeploymentContext(getClass().getClassLoader(), inputFactory, new ModuleScopeContainer(), null); + ModelDataObject modelObject = (ModelDataObject) loader.load(null, reader, context); + Assert.assertNotNull(modelObject.getDataObject()); + Assert.assertTrue(modelObject.getDataObject().getString("myAttr").equals("helloworld.HelloWorldImpl")); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/ImportSDOLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/ImportSDOLoaderTestCase.java new file mode 100755 index 0000000000..b2acb139f9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/ImportSDOLoaderTestCase.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.databinding.sdo; + +import java.io.StringReader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.apache.tuscany.databinding.sdo.ImportSDOLoader.SDOType; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; + +/** + * @version $Rev$ $Date$ + */ +public class ImportSDOLoaderTestCase extends TestCase { + private static boolean inited; + + private ImportSDOLoader loader; + private XMLInputFactory xmlFactory; + private DeploymentContext deploymentContext; + + public void testMinimal() throws XMLStreamException, LoaderException { + String xml = "<import.sdo xmlns='http://incubator.apache.org/tuscany/xmlns/databinding/sdo/1.0-incubator-M2'/>"; + XMLStreamReader reader = getReader(xml); + assertTrue(loader.load(null, reader, deploymentContext) instanceof SDOType); + } + + public void testLocation() throws XMLStreamException, LoaderException { + String xml = "<import.sdo xmlns='http://incubator.apache.org/tuscany/xmlns/databinding/sdo/1.0-incubator-M2' location='ipo.xsd'/>"; + XMLStreamReader reader = getReader(xml); + assertTrue(loader.load(null, reader, deploymentContext) instanceof SDOType); + } + + public void testFactory() throws XMLStreamException, LoaderException { + String xml = "<import.sdo xmlns='http://incubator.apache.org/tuscany/xmlns/databinding/sdo/1.0-incubator-M2' " + + "factory='org.apache.tuscany.databinding.sdo.ImportSDOLoaderTestCase$MockFactory'/>"; + XMLStreamReader reader = getReader(xml); + assertFalse(inited); + assertTrue(loader.load(null, reader, deploymentContext) instanceof SDOType); + assertTrue(inited); + } + + protected void setUp() throws Exception { + super.setUp(); + loader = new ImportSDOLoader(null); + xmlFactory = XMLInputFactory.newInstance(); + deploymentContext = new RootDeploymentContext(getClass().getClassLoader(), xmlFactory, null, null); + } + + protected XMLStreamReader getReader(String xml) throws XMLStreamException { + XMLStreamReader reader = xmlFactory.createXMLStreamReader(new StringReader(xml)); + reader.next(); + return reader; + } + + public static class MockFactory { + public static final Object INSTANCE = null; + + static { + ImportSDOLoaderTestCase.inited = true; + } + } +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/SDODataBindingTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/SDODataBindingTestCase.java new file mode 100644 index 0000000000..438de93c76 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/SDODataBindingTestCase.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.databinding.sdo; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.model.DataType; + +import com.example.ipo.sdo.PurchaseOrderType; +import com.example.ipo.sdo.SdoFactory; +import com.example.ipo.sdo.USAddress; +import commonj.sdo.DataObject; + +/** + * + */ +public class SDODataBindingTestCase extends TestCase { + private SDODataBinding binding; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + binding = new SDODataBinding(); + SDOUtil.registerStaticTypes(SdoFactory.class); + } + + public final void testIntrospect() { + DataType<?> dataType = binding.introspect(DataObject.class); + Assert.assertTrue(dataType.getDataBinding().equals(binding.getName())); + Assert.assertTrue(dataType.getPhysical() == DataObject.class && dataType.getLogical() == null); + dataType = binding.introspect(PurchaseOrderType.class); + Assert.assertEquals(PurchaseOrderType.class, dataType.getPhysical()); + Assert.assertEquals(new QName("http://www.example.com/IPO", "PurchaseOrderType"), dataType.getLogical()); + dataType = binding.introspect(USAddress.class); + Assert.assertEquals(USAddress.class, dataType.getPhysical()); + Assert.assertEquals(new QName("http://www.example.com/IPO", "USAddress"), dataType.getLogical()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/SDOTransformerTestCaseBase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/SDOTransformerTestCaseBase.java new file mode 100644 index 0000000000..848dde6e13 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/SDOTransformerTestCaseBase.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.databinding.sdo; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.core.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.model.DataType; + +import com.example.ipo.sdo.PurchaseOrderType; +import com.example.ipo.sdo.SdoFactory; +import com.example.ipo.sdo.USAddress; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +import junit.framework.Assert; +import junit.framework.TestCase; + +/** + * The base class for SDO-related test cases + */ +public abstract class SDOTransformerTestCaseBase extends TestCase { + protected String binding = DataObject.class.getName(); + + protected static final QName orderQName = new QName("http://www.example.com/IPO", "purchaseOrder"); + + protected TransformationContext context; + protected TransformationContext reversedContext; + protected DataObject dataObject; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + SDOUtil.registerStaticTypes(SdoFactory.class); + context = new TransformationContextImpl(); + context.setSourceDataType(getSourceDataType()); + context.setTargetDataType(getTargetDataType()); + + reversedContext = new TransformationContextImpl(); + reversedContext.setSourceDataType(getTargetDataType()); + reversedContext.setTargetDataType(getSourceDataType()); + + PurchaseOrderType po = SdoFactory.INSTANCE.createPurchaseOrderType(); + USAddress address = SdoFactory.INSTANCE.createUSAddress(); + address.setCity("San Jose"); + address.setStreet("123 ABC St"); + address.setState("CA"); + address.setStreet("95131"); + po.setBillTo(address); + dataObject = (DataObject) po; + } + + protected abstract DataType<?> getSourceDataType(); + + protected abstract DataType<?> getTargetDataType(); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/XMLDocument2XMLStreamReaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/XMLDocument2XMLStreamReaderTestCase.java new file mode 100644 index 0000000000..a7f391216b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/java/org/apache/tuscany/databinding/sdo/XMLDocument2XMLStreamReaderTestCase.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.databinding.sdo; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; + +import org.apache.tuscany.spi.model.DataType; + +import com.example.ipo.sdo.PurchaseOrderType; + +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +/** + * + */ +public class XMLDocument2XMLStreamReaderTestCase extends SDOTransformerTestCaseBase { + + @Override + protected DataType<?> getSourceDataType() { + return new DataType<QName>(XMLDocument.class.getName(), XMLDocument.class, orderQName); + } + + @Override + protected DataType<?> getTargetDataType() { + return new DataType<Class<XMLStreamReader>>(XMLStreamReader.class, XMLStreamReader.class); + } + + public final void testTransform() throws XMLStreamException { + XMLDocument document = + XMLHelper.INSTANCE.createDocument(dataObject, orderQName.getNamespaceURI(), orderQName.getLocalPart()); + XMLStreamReader reader = new XMLDocument2XMLStreamReader().transform(document, context); + XMLDocument document2 = new XMLStreamReader2XMLDocument().transform(reader, reversedContext); + Assert.assertEquals(orderQName.getNamespaceURI(), document2.getRootElementURI()); + Assert.assertEquals(orderQName.getLocalPart(), document2.getRootElementName()); + Assert.assertTrue(document2.getRootObject() instanceof PurchaseOrderType); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/META-INF/tuscany/databinding.sdo.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/META-INF/tuscany/databinding.sdo.scdl new file mode 100644 index 0000000000..70b4028e8a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/META-INF/tuscany/databinding.sdo.scdl @@ -0,0 +1,34 @@ +<?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. +--> +<!-- + import.sdo configuration + + $Rev: 431086 $ $Date: 2006-08-12 13:58:17 -0700 (Sat, 12 Aug 2006) $ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2" + name="org.apache.tuscany.databinding.sdo"> + + <!-- import.sdo element loader implementations --> + <component name="elementLoader.import.sdo"> + <system:implementation.system class="org.apache.tuscany.databinding.sdo.ImportSDOLoader"/> + </component> + +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/ipo.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/ipo.xsd new file mode 100755 index 0000000000..241ec15d36 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/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-M2/sca/services/databinding/databinding-sdo/src/test/resources/model/sca-core.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/model/sca-core.xsd new file mode 100755 index 0000000000..56c6977254 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/model/sca-core.xsd @@ -0,0 +1,233 @@ +<?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. +--> +<schema xmlns="http://www.w3.org/2001/XMLSchema" + targetNamespace="http://www.osoa.org/xmlns/sca/0.9" + xmlns:sca="http://www.osoa.org/xmlns/sca/0.9" + elementFormDefault="qualified"> + + <element name="componentType" type="sca:ComponentType"/> + <complexType name="ComponentType"> + <sequence> + <element minOccurs="0" maxOccurs="unbounded" name="service" type="sca:Service"/> + <element minOccurs="0" maxOccurs="unbounded" name="reference" type="sca:Reference"/> + <element minOccurs="0" maxOccurs="unbounded" name="property" type="sca:Property"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + <complexType name="Service"> + <sequence> + <element minOccurs="1" maxOccurs="1" ref="sca:interface"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + <element name="interface" type="sca:Interface"/> + <complexType name="Interface"/> + + <complexType name="Reference"> + <sequence> + <element minOccurs="1" maxOccurs="1" ref="sca:interface"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <attribute name="multiplicity" type="sca:Multiplicity" use="optional" default="1..1"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + <complexType name="Property"> + <sequence> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <attribute name="type" type="QName" use="required"/> + <attribute name="many" type="boolean" default="false" use="optional"/> + <attribute name="required" type="boolean" default="false" use="optional"/> + <attribute name="default" type="string" use="optional"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + + <element name="moduleFragment" type="sca:ModuleFragment"/> + <complexType name="ModuleFragment"> + <sequence> + <element minOccurs="0" maxOccurs="unbounded" name="entryPoint" type="sca:EntryPoint"/> + <element minOccurs="0" maxOccurs="unbounded" name="component" type="sca:Component"/> + <element minOccurs="0" maxOccurs="unbounded" name="externalService" type="sca:ExternalService"/> + <element minOccurs="0" maxOccurs="unbounded" name="wire" type="sca:ModuleWire"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + <element name="module" type="sca:Module"/> + <complexType name="Module"> + <complexContent> + <extension base="sca:ModuleFragment"/> + </complexContent> + </complexType> + + <complexType name="EntryPoint"> + <sequence> + <element minOccurs="0" maxOccurs="1" ref="sca:interface"/> + <element minOccurs="1" maxOccurs="unbounded" ref="sca:binding"/> + <element minOccurs="1" maxOccurs="unbounded" name="reference" type="anyURI"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <attribute name="multiplicity" type="sca:Multiplicity" use="optional" default="1..1"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + <!-- a multiplicity 1..1 or 0..n sample + <reference>StockQuoteComponent</reference> - type must be URI + a multiplicity 1..n or 0..n sample + <reference>StockQuoteComponent1</reference> - type must be URI + <reference>StockQuoteComponent2</reference> + --> + + <element name="binding" type="sca:Binding"/> + <complexType name="Binding"> + <attribute name="uri" type="anyURI" use="optional"/> + </complexType> + + <complexType name="Component"> + <sequence> + <element minOccurs="1" maxOccurs="1" ref="sca:implementation"/> + <element minOccurs="0" maxOccurs="1" name="properties" type="sca:PropertyValues"/> + <element minOccurs="0" maxOccurs="1" name="references" type="sca:ReferenceValues"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + <!-- a multiplicity 1..1 or 0..1 sample + <references> + <v:stockQuote>StockQuoteComponent</v:stockquote> - type must be URI + </references> + a multiplicity 1..n or 0..n sample + <references> + <v:stockQuote>StockQuoteComponent1</v:stockQuote> - type must be URI + <v:stockQuote>StockQuoteComponent2</v:stockQuote> + </references> + --> + + <element name="implementation" type="sca:Implementation"/> + <complexType name="Implementation"/> + + <complexType name="PropertyValues"> + <sequence> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + <complexType name="ReferenceValues"> + <sequence> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + + <complexType name="ExternalService"> + <sequence> + <element minOccurs="1" maxOccurs="1" ref="sca:interface"/> + <element minOccurs="0" maxOccurs="unbounded" ref="sca:binding"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <attribute name="overridable" type="sca:OverrideOptions" default="may" use="optional"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + + <complexType name="ModuleWire"> + <sequence> + <element minOccurs="1" maxOccurs="1" ref="sca:source.uri"/> + <element minOccurs="1" maxOccurs="1" ref="sca:target.uri"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + <element name="source" type="anyType"/> + <element name="target" type="anyType"/> + + <element name="source.uri" type="anyURI" substitutionGroup="sca:source"/> + <element name="target.uri" type="anyURI" substitutionGroup="sca:target"/> + + <element name="subsystem" type="sca:Subsystem"/> + <complexType name="Subsystem"> + <sequence> + <element minOccurs="0" maxOccurs="unbounded" name="entryPoint" type="sca:EntryPoint"/> + <element minOccurs="0" maxOccurs="unbounded" name="moduleComponent" type="sca:ModuleComponent"/> + <element minOccurs="0" maxOccurs="unbounded" name="externalService" type="sca:ExternalService"/> + <element minOccurs="0" maxOccurs="unbounded" name="wire" type="sca:SystemWire"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <attribute name="uri" type="anyURI" use="optional"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + <complexType name="ModuleComponent"> + <sequence> + <element minOccurs="0" maxOccurs="1" name="properties" type="sca:PropertyValues"/> + <element minOccurs="0" maxOccurs="1" name="references" type="sca:ReferenceValues"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + <attribute name="name" type="NCName" use="required"/> + <attribute name="module" type="NCName" use="required"/> + <attribute name="uri" type="anyURI" use="optional"/> + <anyAttribute namespace="##any" processContents="lax"/> + </complexType> + + <complexType name="SystemWire"> + <sequence> + <element minOccurs="1" maxOccurs="1" ref="sca:source"/> + <element minOccurs="1" maxOccurs="1" ref="sca:target"/> + <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> + </sequence> + </complexType> + + <element name="source.epr" type="anyType" substitutionGroup="sca:source"/> + <element name="target.epr" type="anyType" substitutionGroup="sca:target"/> + + <simpleType name="Multiplicity"> + <restriction base="string"> + <enumeration value="0..1"/> + <enumeration value="1..1"/> + <enumeration value="0..n"/> + <enumeration value="1..n"/> + </restriction> + </simpleType> + + <simpleType name="OverrideOptions"> + <restriction base="string"> + <enumeration value="no"/> + <enumeration value="may"/> + <enumeration value="must"/> + </restriction> + </simpleType> + +</schema> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/model/sca-implementation-mock.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/model/sca-implementation-mock.xsd new file mode 100755 index 0000000000..bbaf58f00c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-sdo/src/test/resources/model/sca-implementation-mock.xsd @@ -0,0 +1,43 @@ +<?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. +--> +<schema xmlns="http://www.w3.org/2001/XMLSchema" + targetNamespace="http://www.osoa.org/xmlns/mock/0.9" + elementFormDefault="qualified" + xmlns:mock="http://www.osoa.org/xmlns/mock/0.9" + xmlns:sca="http://www.osoa.org/xmlns/sca/0.9"> + + <import namespace="http://www.osoa.org/xmlns/sca/0.9" + schemaLocation="sca-core.xsd" /> + + <element name="implementation.mock" type="mock:MockImplementation" + substitutionGroup="sca:implementation" /> + <complexType name="MockImplementation"> + <complexContent> + <extension base="sca:Implementation"> + <sequence> + <any namespace="##other" processContents="lax" + minOccurs="0" maxOccurs="unbounded" /> + </sequence> + <attribute name="myAttr" type="NCName" use="required" /> + <anyAttribute namespace="##any" processContents="lax" /> + </extension> + </complexContent> + </complexType> +</schema> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/LICENSE.txt new file mode 100755 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/pom.xml new file mode 100755 index 0000000000..6a91a4007f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/pom.xml @@ -0,0 +1,217 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>databinding-test</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany Data Binding Integration Test</name> + <description>Apache Tuscany Data Binding Integration Test</description> + + <repositories> + <repository> + <snapshots> + <enabled>true</enabled> + </snapshots> + <id>java.net</id> + <name>java.net Maven 1.x Repository</name> + <url>https://maven-repository.dev.java.net/nonav/repository</url> + <layout>legacy</layout> + </repository> + </repositories> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>databinding-jaxb</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>databinding-xmlbeans</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>databinding-axiom</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>databinding-sdo</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>wsdl</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <version>2.0.2</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>test</artifactId> + <version>${sca.version}</version> + <scope>test</scope> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>1.0</version> + <executions> + <execution> + <id>add-test-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-test-source</goal> + </goals> + <configuration> + <sources> + <source>target/jaxb-source</source> + <source>target/sdo-source</source> + <source>target/xmlbeans-source</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.tuscany.sdo</groupId> + <artifactId>tuscany-sdo-plugin</artifactId> + <executions> + <execution> + <id>generate-sdo</id> + <phase>generate-sources</phase> + <configuration> + <schemaFile>${basedir}/src/test/resources/ipo.xsd</schemaFile> + <javaPackage>com.example.ipo.sdo</javaPackage> + <noNotification>true</noNotification> + <noContainer>true</noContainer> + <noUnsettable>true</noUnsettable> + </configuration> + <goals> + <goal>generate</goal> + </goals> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>com.sun.tools.xjc.maven2</groupId> + <artifactId>maven-jaxb-plugin</artifactId> + <version>1.0</version> + <executions> + <execution> + <id>generate-jaxb</id> + <phase>generate-sources</phase> + <goals> + <goal>generate</goal> + </goals> + </execution> + </executions> + <configuration> + <generatePackage>com.example.ipo.jaxb</generatePackage> + <generateDirectory>${project.build.directory}/jaxb-source</generateDirectory> + <schemaDirectory>${basedir}/src/test/resources</schemaDirectory> + <includeSchemas> + <includeSchema>ipo.xsd</includeSchema> + </includeSchemas> + </configuration> + </plugin> + + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>xmlbeans</groupId> + <artifactId>xbean</artifactId> + <version>2.1.0</version> + </dependency> + <dependency> + <groupId>stax</groupId> + <artifactId>stax-api</artifactId> + <version>1.0.1</version> + </dependency> + + </dependencies> + + <executions> + <execution> + <id>generate-xmlbeans</id> + <phase>generate-sources</phase> + <configuration> + <tasks> + <taskdef name="xmlbean" classname="org.apache.xmlbeans.impl.tool.XMLBean" + classpathref="maven.compile.classpath" /> + <xmlbean schema="${basedir}/src/test/resources" classpathref="maven.compile.classpath" + destfile="${project.build.directory}/ipo-xmlbeans.jar" + srcgendir="${project.build.directory}/xmlbeans-source" javasource="1.5" + classgendir="${project.build.directory}/test-classes" /> + </tasks> + <!-- + <sourceRoot>${project.build.directory}/xmlbeans-source</sourceRoot> + <testSourceRoot>${project.build.directory}/xmlbeans-source</testSourceRoot> + --> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/JAXBTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/JAXBTestCase.java new file mode 100755 index 0000000000..894bee16e4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/JAXBTestCase.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.databinding; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +import java.io.StringReader; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.databinding.jaxb.JAXB2Node; +import org.apache.tuscany.databinding.jaxb.JAXBContextHelper; +import org.apache.tuscany.databinding.jaxb.XMLStreamReader2JAXB; +import org.apache.tuscany.databinding.xmlbeans.Node2XmlObject; +import org.apache.tuscany.databinding.xmlbeans.XmlObject2XMLStreamReader; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.model.DataType; +import org.apache.xmlbeans.XmlObject; +import org.w3c.dom.Node; + +public class JAXBTestCase 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 String contextPath = "com.example.ipo.jaxb"; + + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransform() throws Exception { + // URL/Stream/Reader to XmlObject + XmlObject object = XmlObject.Factory.parse(new StringReader(IPO_XML)); + + // XmlObject to XMLStreamReader + XmlObject2XMLStreamReader t1 = new XmlObject2XMLStreamReader(); + XMLStreamReader reader = t1.transform(object, null); + + DataType targetDataType = new DataType<Class>(Object.class, null); + targetDataType.setMetadata(JAXBContextHelper.JAXB_CONTEXT_PATH, contextPath); + + TransformationContext tContext = createMock(TransformationContext.class); + expect(tContext.getTargetDataType()).andReturn(targetDataType).anyTimes(); + replay(tContext); + + // XMLStreamReader to JAXB + XMLStreamReader2JAXB t2 = new XMLStreamReader2JAXB(); + Object object2 = t2.transform(reader, tContext); + + DataType sourceDataType = new DataType<Class>(Object.class, null); + sourceDataType.setMetadata(JAXBContextHelper.JAXB_CONTEXT_PATH, contextPath); + + TransformationContext tContext1 = createMock(TransformationContext.class); + expect(tContext1.getSourceDataType()).andReturn(sourceDataType).anyTimes(); + replay(tContext1); + + JAXB2Node t3 = new JAXB2Node(); + Node node = t3.transform(object2, tContext1); + + Node2XmlObject t4 = new Node2XmlObject(); + XmlObject object3 = t4.transform(node, null); + + Assert.assertNotNull(object3); + + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/TransformationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/TransformationTestCase.java new file mode 100755 index 0000000000..a181c80b87 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/TransformationTestCase.java @@ -0,0 +1,250 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.databinding; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +import java.io.StringReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.core.databinding.impl.TransformerRegistryImpl; +import org.apache.tuscany.core.databinding.xml.Node2String; +import org.apache.tuscany.core.databinding.xml.String2Node; +import org.apache.tuscany.core.databinding.xml.String2XMLStreamReader; +import org.apache.tuscany.core.databinding.xml.XMLStreamReader2String; +import org.apache.tuscany.databinding.axiom.OMElement2String; +import org.apache.tuscany.databinding.axiom.OMElement2XMLStreamReader; +import org.apache.tuscany.databinding.axiom.String2OMElement; +import org.apache.tuscany.databinding.axiom.XMLStreamReader2OMElement; +import org.apache.tuscany.databinding.jaxb.JAXB2Node; +import org.apache.tuscany.databinding.jaxb.JAXBContextHelper; +import org.apache.tuscany.databinding.jaxb.Node2JAXB; +import org.apache.tuscany.databinding.jaxb.XMLStreamReader2JAXB; +import org.apache.tuscany.databinding.sdo.DataObject2XMLStreamReader; +import org.apache.tuscany.databinding.sdo.XMLDocument2XMLStreamReader; +import org.apache.tuscany.databinding.sdo.XMLStreamReader2DataObject; +import org.apache.tuscany.databinding.sdo.XMLStreamReader2XMLDocument; +import org.apache.tuscany.databinding.sdo.ImportSDOLoader.SDOType; +import org.apache.tuscany.databinding.xmlbeans.Node2XmlObject; +import org.apache.tuscany.databinding.xmlbeans.XMLStreamReader2XmlObject; +import org.apache.tuscany.databinding.xmlbeans.XmlObject2Node; +import org.apache.tuscany.databinding.xmlbeans.XmlObject2XMLStreamReader; +import org.apache.tuscany.sdo.util.SDOUtil; +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.TransformerRegistry; +import org.apache.tuscany.spi.model.DataType; +import org.apache.xmlbeans.XmlObject; +import org.w3c.dom.Node; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; +import commonj.sdo.helper.XSDHelper; + +public class TransformationTestCase 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 TransformerRegistry registry; + + private String contextPath = "com.example.ipo.jaxb"; + + protected void setUp() throws Exception { + super.setUp(); + registry = new TransformerRegistryImpl(); + + List<Transformer> transformers = new ArrayList<Transformer>(); + + // Adding JAXB transformers + transformers.add(new JAXB2Node()); + transformers.add(new Node2JAXB()); + transformers.add(new XMLStreamReader2JAXB()); + + // Adding XMLBeans transformers + transformers.add(new XmlObject2Node()); + transformers.add(new XmlObject2XMLStreamReader()); + transformers.add(new Node2XmlObject()); + transformers.add(new XMLStreamReader2XmlObject()); + + transformers.add(new DataObject2XMLStreamReader()); + transformers.add(new XMLStreamReader2DataObject()); + + transformers.add(new XMLDocument2XMLStreamReader()); + transformers.add(new XMLStreamReader2XMLDocument()); + + transformers.add(new String2XMLStreamReader()); + transformers.add(new XMLStreamReader2String()); + + transformers.add(new String2Node()); + transformers.add(new Node2String()); + + transformers.add(new OMElement2String()); + transformers.add(new String2OMElement()); + + transformers.add(new XMLStreamReader2OMElement()); + transformers.add(new OMElement2XMLStreamReader()); + + for (Transformer transformer : transformers) { + registry.registerTransformer(transformer); + } + + // System.out.println(registry); + + URL xsdFile = getClass().getClassLoader().getResource("ipo.xsd"); + XSDHelper.INSTANCE.define(xsdFile.openStream(), null); + } + + @SuppressWarnings("unchecked") + // XMLBeans --> SDO + public void testTransformation1() throws Exception { + URL xsdFile = getClass().getClassLoader().getResource("ipo.xsd"); + TypeHelper typeHelper = SDOUtil.createTypeHelper(); + XSDHelper xsdHelper = SDOUtil.createXSDHelper(typeHelper); + xsdHelper.define(xsdFile.openStream(), xsdFile.toExternalForm()); + + // URL/Stream/Reader to XmlObject + XmlObject object = XmlObject.Factory.parse(new StringReader(IPO_XML)); + + List<Transformer> path = + registry.getTransformerChain(XmlObject.class.getName(), DataObject.class.getName()); + System.out.println("Path: " + path); + + TransformationContext tContext = createTransformationContext(); + tContext.getMetadata().put(SDOType.class, new SDOType(typeHelper)); + + Object result = object; + for (Transformer transformer : path) { + result = ((PullTransformer)transformer).transform(result, tContext); + } + System.out.println("Result: " + result); + Assert.assertNotNull(result); + Assert.assertTrue(result instanceof DataObject); + + } + + @SuppressWarnings("unchecked") + // SDO --> DOM + public void testTransformation2() throws Exception { + // System.out.println(registry); + + URL xmlFile = getClass().getClassLoader().getResource("ipo.xml"); + // URL/Stream/Reader to XmlObject + XMLDocument object = XMLHelper.INSTANCE.load(xmlFile.openStream()); + + List<Transformer> path = + registry.getTransformerChain(XMLDocument.class.getName(), Node.class.getName()); + System.out.println("Path: " + path); + + TransformationContext tContext = createTransformationContext(); + + Object result = object; + for (Transformer transformer : path) { + result = ((PullTransformer)transformer).transform(result, tContext); + } + System.out.println("Result: " + result); + Assert.assertNotNull(result); + Assert.assertTrue(result instanceof Node); + + } + + @SuppressWarnings("unchecked") + // SDO --> JAXB + public void testTransformation3() throws Exception { + // System.out.println(registry); + + URL xmlFile = getClass().getClassLoader().getResource("ipo.xml"); + // URL/Stream/Reader to XmlObject + XMLDocument object = XMLHelper.INSTANCE.load(xmlFile.openStream()); + + List<Transformer> path = + registry.getTransformerChain(XMLDocument.class.getName(), JAXBElement.class.getName()); + System.out.println("Path: " + path); + + TransformationContext tContext = createTransformationContext(); + + Object result = object; + for (Transformer transformer : path) { + result = ((PullTransformer)transformer).transform(result, tContext); + } + System.out.println("Result: " + result); + Assert.assertNotNull(result); + Assert.assertTrue(result instanceof Object); + + } + + private TransformationContext createTransformationContext() { + DataType dataType = new DataType<Class>(Object.class, null); + dataType.setMetadata(JAXBContextHelper.JAXB_CONTEXT_PATH, contextPath); + + TransformationContext tContext = createMock(TransformationContext.class); + expect(tContext.getTargetDataType()).andReturn(dataType).anyTimes(); + + expect(tContext.getSourceDataType()).andReturn(dataType).anyTimes(); + Map<Class<?>, Object> metadata = new HashMap<Class<?>, Object>(); + expect(tContext.getMetadata()).andReturn(metadata).anyTimes(); + replay(tContext); + return tContext; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/XmlObjectTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/XmlObjectTestCase.java new file mode 100755 index 0000000000..78d51352cb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/XmlObjectTestCase.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding; + +import java.io.StringReader; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.databinding.xmlbeans.Node2XmlObject; +import org.apache.tuscany.databinding.xmlbeans.XMLStreamReader2XmlObject; +import org.apache.tuscany.databinding.xmlbeans.XmlObject2Node; +import org.apache.tuscany.databinding.xmlbeans.XmlObject2XMLStreamReader; +import org.apache.xmlbeans.XmlObject; +import org.w3c.dom.Node; + +public class XmlObjectTestCase 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>"; + + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransform() throws Exception { + XmlObject object = XmlObject.Factory.parse(new StringReader(IPO_XML)); + + // XmlObject to XMLStreamReader + XmlObject2XMLStreamReader t1 = new XmlObject2XMLStreamReader(); + XMLStreamReader reader = t1.transform(object, null); + + // XMLStreamReader to XmlObject + XMLStreamReader2XmlObject t2 = new XMLStreamReader2XmlObject(); + XmlObject object2 = t2.transform(reader, null); + + // XmlObject to Node + XmlObject2Node t3 = new XmlObject2Node(); + Node node = t3.transform(object2, null); + + // Node to XmlObject + Node2XmlObject t4 = new Node2XmlObject(); + XmlObject object3 = t4.transform(node, null); + Assert.assertNotNull(object3); + } + + /* + * public void testGeneratedXmlObject() throws Exception { URL xmlFile = + * getClass().getClassLoader().getResource("ipo.xml"); // URL/Stream/Reader + * to XmlObject PurchaseOrderDocument object = + * PurchaseOrderDocument.Factory.parse(xmlFile); // XmlObject to + * XMLStreamReader XmlObject2XMLStreamReader t1 = new + * XmlObject2XMLStreamReader(); XMLStreamReader reader = + * t1.transform(object, null); // XMLStreamReader to XmlObject + * XMLStreamReader2XmlObject t2 = new XMLStreamReader2XmlObject(); XmlObject + * object2 = t2.transform(reader, null); // XmlObject to Node XmlObject2Node + * t3 = new XmlObject2Node(); Node node = t3.transform(object2, null); // + * Node to XmlObject Node2XmlObject t4 = new Node2XmlObject(); XmlObject + * object3 = t4.transform(node, null); Assert.assertNotNull(object3); } + */ + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/Client.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/Client.java new file mode 100644 index 0000000000..8ddc625d66 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/Client.java @@ -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. + */ +package org.apache.tuscany.databinding.sample; + +/** + * @version $Rev$ $Date$ + */ +public interface Client { + void call(Object po); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/ClientImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/ClientImpl.java new file mode 100644 index 0000000000..2d33a8666b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/ClientImpl.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.databinding.sample; + +import org.osoa.sca.annotations.Constructor; +import org.osoa.sca.annotations.Reference; + +import com.example.ipo.jaxb.PurchaseOrderType; + +/** + * @version $Rev$ $Date$ + */ +public class ClientImpl implements Client { + + private Echo echoReference; + + @Constructor + public ClientImpl(@Reference(name = "echoReference", required = true) + Echo echoReference) { + this.echoReference = echoReference; + } + + public void call(Object po) { + Object ret = null; + if (po instanceof PurchaseOrderType) { + ret = echoReference.echoJAXB((PurchaseOrderType)po); + } else if (po instanceof com.example.ipo.sdo.PurchaseOrderType) { + ret = echoReference.echoSDO((com.example.ipo.sdo.PurchaseOrderType)po); + } else if (po instanceof com.example.ipo.xmlbeans.PurchaseOrderType) { + ret = echoReference.echoXMLBeans((com.example.ipo.xmlbeans.PurchaseOrderType)po); + } + System.out.println("Returned message: " + ret); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/DataBindingBootStrapTest.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/DataBindingBootStrapTest.java new file mode 100644 index 0000000000..ff44dfb68d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/DataBindingBootStrapTest.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.sample; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +import java.io.StringReader; + +import javax.xml.bind.JAXBElement; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.databinding.jaxb.JAXBContextHelper; +import org.apache.tuscany.databinding.jaxb.Reader2JAXB; +import org.apache.tuscany.databinding.sdo.String2DataObject; +import org.apache.tuscany.databinding.xmlbeans.XMLStreamReader2XmlObject; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.model.DataType; +import org.apache.tuscany.test.SCATestCase; +import org.osoa.sca.CompositeContext; +import org.osoa.sca.CurrentCompositeContext; + +import com.example.ipo.jaxb.PurchaseOrderType; +import com.example.ipo.xmlbeans.PurchaseOrderDocument; +import commonj.sdo.DataObject; + +/** + * @version $Rev$ $Date$ + */ +public class DataBindingBootStrapTest extends SCATestCase { + 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 Client client; + private String contextPath = "com.example.ipo.jaxb"; + + @SuppressWarnings("unchecked") + public void testDataBindingBootstrap() throws Exception { + DataType targetDataType = new DataType<Class>(Object.class, null); + targetDataType.setMetadata(JAXBContextHelper.JAXB_CONTEXT_PATH, contextPath); + TransformationContext tContext = createMock(TransformationContext.class); + expect(tContext.getTargetDataType()).andReturn(targetDataType).anyTimes(); + replay(tContext); + + String2DataObject t1 = new String2DataObject(); + DataObject po1 = t1.transform(IPO_XML, null); + client.call(po1); + + XMLStreamReader reader = + XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(IPO_XML)); + XMLStreamReader2XmlObject t2 = new XMLStreamReader2XmlObject(); + PurchaseOrderDocument po2 = (PurchaseOrderDocument)t2.transform(reader, null); + client.call(po2.getPurchaseOrder()); + + Reader2JAXB t3 = new Reader2JAXB(); + JAXBElement<PurchaseOrderType> po3 = + (JAXBElement<PurchaseOrderType>)t3.transform(new StringReader(IPO_XML), tContext); + client.call(po3.getValue()); + + } + + protected void setUp() throws Exception { + setApplicationSCDL(getClass(), "META-INF/sca/default.scdl"); + addExtension("test-extensions", getClass().getClassLoader() + .getResource("META-INF/tuscany/test-extensions.scdl")); + super.setUp(); + CompositeContext context = CurrentCompositeContext.getContext(); + client = context.locateService(Client.class, "Client"); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/Echo.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/Echo.java new file mode 100644 index 0000000000..c44e575e26 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/Echo.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.databinding.sample; + +import org.apache.tuscany.api.annotation.DataType; +import org.osoa.sca.annotations.Remotable; +import org.osoa.sca.annotations.Service; + +import com.example.ipo.jaxb.PurchaseOrderType; + + +/** + * @version $Rev$ $Date$ + */ +@Remotable +@Service +public interface Echo { + @DataType(name="javax.xml.bind.JAXBElement") + PurchaseOrderType echoJAXB(PurchaseOrderType po); + + @DataType(name="commonj.sdo.DataObject") + com.example.ipo.sdo.PurchaseOrderType echoSDO(com.example.ipo.sdo.PurchaseOrderType po); + + @DataType(name="org.apache.xmlbeans.XmlObject") + com.example.ipo.xmlbeans.PurchaseOrderType echoXMLBeans(com.example.ipo.xmlbeans.PurchaseOrderType po); +}
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/EchoImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/EchoImpl.java new file mode 100644 index 0000000000..775c0317a4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/java/org/apache/tuscany/databinding/sample/EchoImpl.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.databinding.sample; + +import com.example.ipo.jaxb.PurchaseOrderType; + +/** + * @version $Rev$ $Date$ + */ +public class EchoImpl implements Echo { + + public PurchaseOrderType echoJAXB(PurchaseOrderType po) { + System.out.println("JAXB: " + po); + return po; + } + + public com.example.ipo.sdo.PurchaseOrderType echoSDO(com.example.ipo.sdo.PurchaseOrderType po) { + System.out.println("SDO: " + po); + return po; + } + + public com.example.ipo.xmlbeans.PurchaseOrderType echoXMLBeans(com.example.ipo.xmlbeans.PurchaseOrderType po) { + System.out.println("XMLBeans: " + po); + return po; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..611acdb919 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/sca/default.scdl @@ -0,0 +1,34 @@ +<?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.
+--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:db="http://incubator.apache.org/tuscany/xmlns/databinding/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.sample">
+ + <dbsdo:import.sdo xmlns:dbsdo="http://incubator.apache.org/tuscany/xmlns/databinding/sdo/1.0-incubator-M2" factory="com.example.ipo.sdo.SdoFactory"/>
+ + <component name="Client"> + <implementation.java class="org.apache.tuscany.databinding.sample.ClientImpl" /> + <reference name="echoReference">Echo</reference> + </component> +
+ <component name="Echo">
+ <implementation.java class="org.apache.tuscany.databinding.sample.EchoImpl" />
+ </component>
+ +</composite> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.axiom.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.axiom.scdl new file mode 100644 index 0000000000..a21da8c6e2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.axiom.scdl @@ -0,0 +1,52 @@ +<?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.
+--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.Axiom">
+
+ <component name="databinding.axiom">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.AxiomDataBinding" />
+ </component>
+
+ <!-- Transformers -->
+ <component name="transformer.XMLStreamReader2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.XMLStreamReader2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2XMLStreamReader">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2XMLStreamReader" />
+ </component>
+
+ <component name="transformer.String2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.String2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2String">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2String" />
+ </component>
+
+ <component name="transformer.Object2OMElement">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.Object2OMElement" />
+ </component>
+
+ <component name="transformer.OMElement2Object">
+ <system:implementation.system class="org.apache.tuscany.databinding.axiom.OMElement2Object" />
+ </component>
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.jaxb.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.jaxb.scdl new file mode 100644 index 0000000000..2b86e506eb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.jaxb.scdl @@ -0,0 +1,43 @@ +<?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.
+--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.JAXB">
+
+ <component name="databinding.jaxb">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.JAXBDataBinding" />
+ </component>
+
+ <component name="transformer.XMLStreamReader2JAXB">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.XMLStreamReader2JAXB" />
+ </component>
+
+ <component name="transformer.Node2JAXB">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.Node2JAXB" />
+ </component>
+
+ <component name="transformer.JAXB2Node">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.JAXB2Node" />
+ </component>
+
+ <component name="transformer.Reader2JAXB">
+ <system:implementation.system class="org.apache.tuscany.databinding.jaxb.Reader2JAXB" />
+ </component>
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.sdo.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.sdo.scdl new file mode 100644 index 0000000000..dabab7c687 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.sdo.scdl @@ -0,0 +1,58 @@ +<?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.
+-->
+<!--
+ import.sdo configuration
+
+ $Rev: 431086 $ $Date: 2006-08-12 13:58:17 -0700 (Sat, 12 Aug 2006) $
+-->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0"
+ xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.sdo">
+
+ <!-- import.sdo element loader implementations -->
+ <component name="elementLoader.import.sdo">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.ImportSDOLoader"/>
+ </component>
+ <component name="databinding.sdo">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.SDODataBinding" />
+ </component>
+ <component name="transformer.DataObject2String">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.DataObject2String"/>
+ </component>
+ <component name="transformer.DataObject2XMLStreamReader">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.DataObject2XMLStreamReader"/>
+ </component>
+ <component name="transformer.XMLDocument2String">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLDocument2String"/>
+ </component>
+ <component name="transformer.String2DataObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.String2DataObject"/>
+ </component>
+ <component name="transformer.XMLDocument2XMLStreamReader">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLDocument2XMLStreamReader"/>
+ </component>
+ <component name="transformer.XMLStreamReader2DataObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLStreamReader2DataObject"/>
+ </component>
+ <component name="transformer.XMLStreamReader2XMLDocument">
+ <system:implementation.system class="org.apache.tuscany.databinding.sdo.XMLStreamReader2XMLDocument"/>
+ </component>
+
+</composite>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.xmlbeans.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.xmlbeans.scdl new file mode 100644 index 0000000000..55c7363cba --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/databinding.xmlbeans.scdl @@ -0,0 +1,43 @@ +<?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.
+--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.XMLBeans">
+
+ <component name="databinding.XMLBeans">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.XMLBeansDataBinding" />
+ </component>
+
+ <component name="transformer.XMLStreamReader2XmlObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.XMLStreamReader2XmlObject" />
+ </component>
+
+ <component name="transformer.Node2XmlObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.Node2XmlObject" />
+ </component>
+
+ <component name="transformer.XmlObject2Node">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.XmlObject2Node" />
+ </component>
+
+ <component name="transformer.XMLStreamReader2XmlObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.XMLStreamReader2XmlObject" />
+ </component>
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/interface.wsdl.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/interface.wsdl.scdl new file mode 100644 index 0000000000..fe9a635747 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/interface.wsdl.scdl @@ -0,0 +1,44 @@ +<?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.
+-->
+<!--
+ Default system configuration for the launcher environment.
+
+ $Rev: 440894 $ $Date: 2006-09-06 15:52:01 -0700 (Wed, 06 Sep 2006) $
+-->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.idl.WSDL">
+
+ <component name="interface.wsdl.Loader">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.InterfaceWSDLLoader" />
+ </component>
+
+ <component name="wsdl.Registry">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistryImpl" initLevel="40" />
+ </component>
+
+ <component name="xmlSchema.registry">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.XMLSchemaRegistryImpl" initLevel="35" />
+ </component>
+
+ <component name="interface.wsdl.Introspector">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.InterfaceWSDLIntrospectorImpl" initLevel="40" />
+ </component>
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/test-extensions.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/test-extensions.scdl new file mode 100644 index 0000000000..193bd7a3f6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/META-INF/tuscany/test-extensions.scdl @@ -0,0 +1,30 @@ +<?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.
+--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="test.extensions">
+
+ <include name="org.apache.tuscany.databinding.axiom" scdlLocation="databinding.axiom.scdl"/>
+ <include name="org.apache.tuscany.databinding.sdo" scdlLocation="databinding.sdo.scdl"/>
+ <include name="org.apache.tuscany.databinding.jaxb" scdlLocation="databinding.jaxb.scdl"/>
+ <include name="org.apache.tuscany.databinding.xmlbeans" scdlLocation="databinding.xmlbeans.scdl"/>
+ <include name="org.apache.tuscany.interface.wsdl" scdlLocation="interface.wsdl.scdl"/>
+
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/ipo.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/ipo.xml new file mode 100755 index 0000000000..df901d183d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/ipo.xml @@ -0,0 +1,51 @@ +<?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. +--> +<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> + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/ipo.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/ipo.xsd new file mode 100755 index 0000000000..241ec15d36 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/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-M2/sca/services/databinding/databinding-test/src/test/resources/ipo.xsdconfig b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/ipo.xsdconfig new file mode 100755 index 0000000000..a397182672 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-test/src/test/resources/ipo.xsdconfig @@ -0,0 +1,21 @@ +<!-- Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. --> +<xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config" + xmlns:ipo="http://www.example.com/IPO"> + + <xb:namespace uri="http://www.example.com/IPO"> + <xb:package>com.example.ipo.xmlbeans</xb:package> + </xb:namespace> + +</xb:config> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/LICENSE.txt new file mode 100755 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/pom.xml new file mode 100755 index 0000000000..84fcdef7c8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/pom.xml @@ -0,0 +1,98 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>databinding-xmlbeans</artifactId> + <name>Apache Tuscany Data Binding for XmlBeans</name> + <description>Tuscany XmlBeans Data Binding</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>xmlbeans</groupId> + <artifactId>xbean</artifactId> + <version>2.1.0</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>1.0</version> + <executions> + <execution> + <id>add-test-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-test-source</goal> + </goals> + <configuration> + <sources> + <source>target/xmlbeans-source</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>generate-xmlbeans</id> + <phase>generate-test-sources</phase> + <configuration> + <tasks> + <taskdef name="xmlbean" classname="org.apache.xmlbeans.impl.tool.XMLBean" + classpathref="maven.compile.classpath" /> + <xmlbean schema="${basedir}/src/test/resources" classpathref="maven.compile.classpath" + destfile="${project.build.directory}/ipo-xmlbeans.jar" + srcgendir="${project.build.directory}/xmlbeans-source" javasource="1.5" + classgendir="${project.build.directory}/test-classes" /> + </tasks> + <testSourceRoot>${project.build.directory}/xmlbeans-source</testSourceRoot> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/Node2XmlObject.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/Node2XmlObject.java new file mode 100755 index 0000000000..0b4da53473 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/Node2XmlObject.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.databinding.xmlbeans; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.osoa.sca.annotations.Service; +import org.w3c.dom.Node; + +@Service(Transformer.class) +public class Node2XmlObject extends TransformerExtension<Node, XmlObject> implements + PullTransformer<Node, XmlObject> { + // private XmlOptions options; + + public XmlObject transform(Node source, TransformationContext context) { + try { + return XmlObject.Factory.parse(source); + } catch (XmlException e) { + throw new TransformationException(e); + } + } + + public Class getTargetType() { + return XmlObject.class; + } + + public Class getSourceType() { + return Node.class; + } + + public int getWeight() { + return 30; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XMLBeansDataBinding.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XMLBeansDataBinding.java new file mode 100644 index 0000000000..12057982e4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XMLBeansDataBinding.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.databinding.xmlbeans; + +import org.apache.tuscany.spi.databinding.extension.DataBindingExtension; +import org.apache.xmlbeans.XmlObject; + +/** + * XMLBeans DataBinding + */ +public class XMLBeansDataBinding extends DataBindingExtension { + public static final String NAME = XmlObject.class.getName(); + + public XMLBeansDataBinding() { + super(NAME, XmlObject.class); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XMLStreamReader2XmlObject.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XMLStreamReader2XmlObject.java new file mode 100755 index 0000000000..0e61bd9571 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XMLStreamReader2XmlObject.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.databinding.xmlbeans; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformationException; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.osoa.sca.annotations.Service; + +@Service(Transformer.class) +public class XMLStreamReader2XmlObject extends TransformerExtension<XMLStreamReader, XmlObject> implements PullTransformer<XMLStreamReader, XmlObject> { + // private XmlOptions options; + + public XmlObject transform(XMLStreamReader source, TransformationContext context) { + try { + return XmlObject.Factory.parse(source); + } catch (XmlException e) { + throw new TransformationException(e); + } + } + + public Class getTargetType() { + return XmlObject.class; + } + + public Class getSourceType() { + return XMLStreamReader.class; + } + + public int getWeight() { + return 10; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XmlObject2Node.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XmlObject2Node.java new file mode 100755 index 0000000000..8fc1e58bd5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XmlObject2Node.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.databinding.xmlbeans; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.apache.xmlbeans.XmlObject; +import org.osoa.sca.annotations.Service; +import org.w3c.dom.Node; + +@Service(Transformer.class) +public class XmlObject2Node extends TransformerExtension<XmlObject, Node> implements + PullTransformer<XmlObject, Node> { + // private XmlOptions options; + + public Node transform(XmlObject source, TransformationContext context) { + if (source == null) + return null; + return source.newDomNode(); + } + + public Class getSourceType() { + return XmlObject.class; + } + + public Class getTargetType() { + return Node.class; + } + + public int getWeight() { + return 30; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XmlObject2XMLStreamReader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XmlObject2XMLStreamReader.java new file mode 100755 index 0000000000..8a12cf34f0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/java/org/apache/tuscany/databinding/xmlbeans/XmlObject2XMLStreamReader.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.databinding.xmlbeans; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.databinding.PullTransformer; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.extension.TransformerExtension; +import org.apache.xmlbeans.XmlObject; + +public class XmlObject2XMLStreamReader extends TransformerExtension<XmlObject, XMLStreamReader> implements PullTransformer<XmlObject, XMLStreamReader> { + // private XmlOptions options; + + public XMLStreamReader transform(XmlObject source, TransformationContext context) { + return source.newXMLStreamReader(); + } + + public Class getSourceType() { + return XmlObject.class; + } + + public Class getTargetType() { + return XMLStreamReader.class; + } + + public int getWeight() { + return 10; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..55c7363cba --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,43 @@ +<?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.
+--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.databinding.XMLBeans">
+
+ <component name="databinding.XMLBeans">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.XMLBeansDataBinding" />
+ </component>
+
+ <component name="transformer.XMLStreamReader2XmlObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.XMLStreamReader2XmlObject" />
+ </component>
+
+ <component name="transformer.Node2XmlObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.Node2XmlObject" />
+ </component>
+
+ <component name="transformer.XmlObject2Node">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.XmlObject2Node" />
+ </component>
+
+ <component name="transformer.XMLStreamReader2XmlObject">
+ <system:implementation.system class="org.apache.tuscany.databinding.xmlbeans.XMLStreamReader2XmlObject" />
+ </component>
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/test/java/org/apache/tuscany/databinding/xmlbeans/XmlObjectTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/test/java/org/apache/tuscany/databinding/xmlbeans/XmlObjectTestCase.java new file mode 100755 index 0000000000..57fbae7e35 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/test/java/org/apache/tuscany/databinding/xmlbeans/XmlObjectTestCase.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.databinding.xmlbeans; + +import java.io.StringReader; +import java.net.URL; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.xmlbeans.XmlObject; +import org.w3c.dom.Node; + +import com.example.ipo.xmlbeans.PurchaseOrderDocument; + +public class XmlObjectTestCase 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>"; + + protected void setUp() throws Exception { + super.setUp(); + } + + public void testXmlObject() throws Exception { + // URL/Stream/Reader to XmlObject + XmlObject object = XmlObject.Factory.parse(new StringReader(IPO_XML)); + + // XmlObject to XMLStreamReader + XmlObject2XMLStreamReader t1 = new XmlObject2XMLStreamReader(); + XMLStreamReader reader = t1.transform(object, null); + + // XMLStreamReader to XmlObject + XMLStreamReader2XmlObject t2 = new XMLStreamReader2XmlObject(); + XmlObject object2 = t2.transform(reader, null); + + // XmlObject to Node + XmlObject2Node t3 = new XmlObject2Node(); + Node node = t3.transform(object2, null); + + // Node to XmlObject + Node2XmlObject t4 = new Node2XmlObject(); + XmlObject object3 = t4.transform(node, null); + Assert.assertNotNull(object3); + } + + public void testGeneratedXmlObject() throws Exception { + // URL xmlFile = getClass().getClassLoader().getResource("ipo.xml"); + // URL/Stream/Reader to XmlObject + PurchaseOrderDocument object = PurchaseOrderDocument.Factory.parse(new StringReader(IPO_XML)); + + // XmlObject to XMLStreamReader + XmlObject2XMLStreamReader t1 = new XmlObject2XMLStreamReader(); + XMLStreamReader reader = t1.transform(object, null); + + // XMLStreamReader to XmlObject + XMLStreamReader2XmlObject t2 = new XMLStreamReader2XmlObject(); + PurchaseOrderDocument object2 = (PurchaseOrderDocument) t2.transform(reader, null); + + // XmlObject to Node + XmlObject2Node t3 = new XmlObject2Node(); + Node node = t3.transform(object2, null); + + // Node to XmlObject + Node2XmlObject t4 = new Node2XmlObject(); + PurchaseOrderDocument object3 = (PurchaseOrderDocument) t4.transform(node, null); + Assert.assertNotNull(object3); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/test/resources/ipo.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/test/resources/ipo.xsd new file mode 100755 index 0000000000..241ec15d36 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/test/resources/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-M2/sca/services/databinding/databinding-xmlbeans/src/test/resources/ipo.xsdconfig b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/test/resources/ipo.xsdconfig new file mode 100755 index 0000000000..a397182672 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/databinding-xmlbeans/src/test/resources/ipo.xsdconfig @@ -0,0 +1,21 @@ +<!-- Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. --> +<xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config" + xmlns:ipo="http://www.example.com/IPO"> + + <xb:namespace uri="http://www.example.com/IPO"> + <xb:package>com.example.ipo.xmlbeans</xb:package> + </xb:namespace> + +</xb:config> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/pom.xml new file mode 100644 index 0000000000..5c311e470c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/databinding/pom.xml @@ -0,0 +1,60 @@ +<?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> + + <parent> + <groupId>org.apache.tuscany.sca.services</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.tuscany.sca.services.databinding</groupId> + <artifactId>parent</artifactId> + <packaging>pom</packaging> + <name>Tuscany SCA Data Bindings</name> + + <profiles> + <profile> + <id>full</id> + <activation> + <activeByDefault>true</activeByDefault> + </activation> + <modules> + <module>databinding-axiom</module> + <module>databinding-castor</module> + <module>databinding-jaxb</module> + <module>databinding-sdo</module> + <module>databinding-xmlbeans</module> + <module>databinding-test</module> + </modules> + </profile> + <profile> + <id>release</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <modules> + <module>databinding-axiom</module> + <module>databinding-sdo</module> + </modules> + </profile> + </profiles> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/pom.xml new file mode 100644 index 0000000000..10035bfbd3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/pom.xml @@ -0,0 +1,61 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>parent</artifactId> + <packaging>pom</packaging> + <name>Tuscany SCA Interface Definition Languages</name> + + <!-- definition of repositories where the parent pom can be found --> + <repositories> + <repository> + <id>apache.snapshots</id> + <name>Apache Snapshot Repository</name> + <url>http://people.apache.org/repo/m2-snapshot-repository</url> + <releases> + <enabled>false</enabled> + </releases> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>apache.incubator</id> + <name>Apache Incubator Repository</name> + <url>http://people.apache.org/repo/m2-incubating-repository/</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + + <modules> + <module>wsdl</module> + </modules> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/.ruleset new file mode 100644 index 0000000000..3886f07f2d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/.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-M2/sca/services/idl/wsdl/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/LICENSE.txt new file mode 100644 index 0000000000..0084319535 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, serviceDefinition 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-M2/sca/services/idl/wsdl/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/pom.xml new file mode 100644 index 0000000000..6fb9ea427d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/pom.xml @@ -0,0 +1,57 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>wsdl</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany WSDL</name> + <description>Tuscany WSDL Support.</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.ws.commons.schema</groupId> + <artifactId>XmlSchema</artifactId> + </dependency> + + <dependency> + <groupId>wsdl4j</groupId> + <artifactId>wsdl4j</artifactId> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospector.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospector.java new file mode 100644 index 0000000000..1b9326acab --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospector.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.idl.wsdl; + +import javax.wsdl.PortType; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; + +/** + * Introspector for creating WSDLServiceContract definitions from WSDL PortTypes. + * + * @version $Rev$ $Date$ + */ +public interface InterfaceWSDLIntrospector { + + /** + * Introspect a WSDL portType and return a service contract definition. + * + * @param type the portType to inspect + * @return a WSDLServiceContract corresponding to the WSDL portType + */ + WSDLServiceContract introspect(PortType portType) throws InvalidServiceContractException; + + /** + * Introspect a WSDL portType and return a service contract definition. + * + * @param type the portType to inspect + * @param callback the callback portType to inspec + * @return a WSDLServiceContract corresponding to the WSDL portType + */ + WSDLServiceContract introspect(PortType type, PortType callback) throws InvalidServiceContractException; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospectorImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospectorImpl.java new file mode 100644 index 0000000000..bbfb3b3d01 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospectorImpl.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.idl.wsdl; + +import java.util.HashMap; +import java.util.Map; + +import javax.wsdl.Operation; +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.model.InteractionScope; +import org.osoa.sca.annotations.Constructor; + +/** + * Introspector for creating WSDLServiceContract definitions from WSDL PortTypes. + */ +public class InterfaceWSDLIntrospectorImpl implements InterfaceWSDLIntrospector { + public static final String INPUT_PARTS = "idl:input"; + + private WSDLDefinitionRegistry wsdlDefinitionRegistry; + + /** + * @param wsdlDefinitionRegistry + */ + @Constructor("wsdlDefinitionRegistry") + public InterfaceWSDLIntrospectorImpl(@Autowire WSDLDefinitionRegistry wsdlDefinitionRegistry) { + super(); + this.wsdlDefinitionRegistry = wsdlDefinitionRegistry; + } + + // FIXME: Do we want to deal with document-literal wrapped style based on the JAX-WS spec? + protected Map<String, org.apache.tuscany.spi.model.Operation<QName>> introspectOperations(PortType portType) + throws InvalidServiceContractException { + Map<String, org.apache.tuscany.spi.model.Operation<QName>> operations = + new HashMap<String, org.apache.tuscany.spi.model.Operation<QName>>(); + for (Object op : portType.getOperations()) { + Operation wsdlOp = (Operation) op; + operations.put(wsdlOp.getName(), introspectOperation(wsdlOp)); + } + return operations; + } + + protected org.apache.tuscany.spi.model.Operation<QName> introspectOperation(Operation wsdlOp) + throws InvalidServiceContractException { + + WSDLOperation op = new WSDLOperation(wsdlOp, null, wsdlDefinitionRegistry.getSchemaRegistry()); + return op.getOperation(); + } + + /** + * @see org.apache.tuscany.idl.wsdl.InterfaceWSDLIntrospector#introspect(javax.wsdl.PortType) + */ + public WSDLServiceContract introspect(PortType portType) throws InvalidServiceContractException { + WSDLServiceContract contract = new WSDLServiceContract(); + contract.setPortType(portType); + contract.setInterfaceName(portType.getQName().getLocalPart()); + contract.setOperations(introspectOperations(portType)); + // FIXME: set to Non-conversational for now + contract.setInteractionScope(InteractionScope.NONCONVERSATIONAL); + return contract; + } + + /** + * @see org.apache.tuscany.idl.wsdl.InterfaceWSDLIntrospector#introspect(javax.wsdl.PortType, javax.wsdl.PortType) + */ + public WSDLServiceContract introspect(PortType portType, PortType callbackPortType) + throws InvalidServiceContractException { + assert portType != null : "PortType cannot be null"; + WSDLServiceContract contract = new WSDLServiceContract(); + // FIXME: set to Non-conversational for now + contract.setInteractionScope(InteractionScope.NONCONVERSATIONAL); + contract.setPortType(portType); + contract.setInterfaceName(portType.getQName().getLocalPart()); + contract.setOperations(introspectOperations(portType)); + if (callbackPortType != null) { + contract.setCallbackPortType(callbackPortType); + contract.setCallbackName(callbackPortType.getQName().getLocalPart()); + contract.setCallbackOperations(introspectOperations(callbackPortType)); + } + return contract; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLLoader.java new file mode 100644 index 0000000000..cdb74becfd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLLoader.java @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.idl.wsdl; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.wsdl.PortType; +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; +import org.osoa.sca.annotations.Constructor; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.loader.InvalidValueException; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; +import org.apache.tuscany.spi.loader.MissingResourceException; +import org.apache.tuscany.spi.model.DataType; +import org.apache.tuscany.spi.model.ModelObject; +import org.apache.tuscany.spi.model.ServiceContract; + +/** + * Loads a WSDL interface definition from an XML-based assembly file + * + * @version $Rev$ $Date$ + */ +public class InterfaceWSDLLoader extends LoaderExtension { + public static final QName INTERFACE_WSDL = new QName(XML_NAMESPACE_1_0, "interface.wsdl"); + + private static final String WSDLI = "http://www.w3.org/2006/01/wsdl-instance"; + + private static final String WSDLI_LOCATION = "wsdlLocation"; + + private WSDLDefinitionRegistry wsdlRegistry; + + private InterfaceWSDLIntrospector introspector; + + @Constructor ({ "registry", "wsdlRegistry", "introspector" }) + public InterfaceWSDLLoader(@Autowire LoaderRegistry registry, + @Autowire WSDLDefinitionRegistry wsdlRegistry, + @Autowire InterfaceWSDLIntrospector introspector) { + super(registry); + this.wsdlRegistry = wsdlRegistry; + this.introspector = introspector; + } + + public QName getXMLType() { + return INTERFACE_WSDL; + } + + public WSDLServiceContract load( + CompositeComponent parent, + XMLStreamReader reader, + DeploymentContext deploymentContext) throws XMLStreamException, LoaderException { + assert INTERFACE_WSDL.equals(reader.getName()); + + String interfaceURI = reader.getAttributeValue(null, "interface"); + if (interfaceURI == null) { + throw new InvalidValueException("interface"); + } + + String callbackURI = reader.getAttributeValue(null, "callbackInterface"); + String wsdlLocation = reader.getAttributeValue(WSDLI, WSDLI_LOCATION); + + Map<Class<?>, ModelObject> extensions = new HashMap<Class<?>, ModelObject>(); + while (true) { + int event = reader.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + ModelObject mo = registry.load(parent, reader, deploymentContext); + if (mo != null) { + extensions.put(mo.getClass(), mo); + } + } else if (event == XMLStreamConstants.END_ELEMENT) { + if (reader.getName().equals(INTERFACE_WSDL)) { + break; + } + } + } + // FIXME set the interaction scope + // serviceContract.setInteractionScope(StAXUtil.interactionScope(reader.getAttributeValue(null, "scope"))); + + if (wsdlLocation != null) { + try { + wsdlRegistry.loadDefinition(wsdlLocation, deploymentContext.getClassLoader()); + } catch (IOException e) { + LoaderException le = new LoaderException(e); + le.setIdentifier(wsdlLocation); + throw le; + } catch (WSDLException e) { + LoaderException le = new LoaderException(e); + le.setIdentifier(wsdlLocation); + throw le; + } + } + + PortType portType = getPortType(interfaceURI); + if (portType == null) { + throw new MissingResourceException(interfaceURI); + } + PortType callback = null; + if (callbackURI != null) { + callback = getPortType(callbackURI); + } + try { + WSDLServiceContract contract = introspector.introspect(portType, callback); + DataType<?> dataType = (DataType<?>) extensions.get(DataType.class); + if (dataType != null) { + contract.setDataBinding(dataType.getDataBinding()); + } + contract.getExtensions().putAll(extensions); + return contract; + } catch (InvalidServiceContractException e) { + LoaderException le = new LoaderException(e); + le.setIdentifier(wsdlLocation); + throw le; + } + } + + protected PortType getPortType(String uri) { + // Syntax: <WSDL-namespace-URI>#wsdl.interface(<portTypeOrInterface-name>) + int index = uri.indexOf('#'); + String namespace = uri.substring(0, index); + String name = uri.substring(index + 1); + name = name.substring("wsdl.interface(".length(), name.length() - 1); + QName qname = new QName(namespace, name); + return wsdlRegistry.getPortType(qname); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidFragmentException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidFragmentException.java new file mode 100644 index 0000000000..55decc9313 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidFragmentException.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +/** + * @version $Rev$ $Date$ + */ +public class InvalidFragmentException extends WSDLLoaderException { + public InvalidFragmentException() { + } + + public InvalidFragmentException(String message) { + super(message); + } + + public InvalidFragmentException(String message, Throwable cause) { + super(message, cause); + } + + public InvalidFragmentException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidWSDLException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidWSDLException.java new file mode 100644 index 0000000000..17dde17b19 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidWSDLException.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.idl.wsdl; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; + +/** + * An exception to indicate the WSDL definition is invalid + */ +public class InvalidWSDLException extends InvalidServiceContractException { + + /** + * + */ + public InvalidWSDLException() { + } + + /** + * @param message + */ + public InvalidWSDLException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public InvalidWSDLException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param cause + */ + public InvalidWSDLException(Throwable cause) { + super(cause); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidWSDLLocationException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidWSDLLocationException.java new file mode 100644 index 0000000000..7c5ab0bfc1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/InvalidWSDLLocationException.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +/** + * @version $Rev$ $Date$ + */ +public class InvalidWSDLLocationException extends WSDLLoaderException { + public InvalidWSDLLocationException() { + } + + public InvalidWSDLLocationException(String message) { + super(message); + } + + public InvalidWSDLLocationException(String message, Throwable cause) { + super(message, cause); + } + + public InvalidWSDLLocationException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/MissingWSDLException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/MissingWSDLException.java new file mode 100644 index 0000000000..92a2b2099e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/MissingWSDLException.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +/** + * @version $Rev$ $Date$ + */ +public class MissingWSDLException extends WSDLLoaderException { + public MissingWSDLException() { + } + + public MissingWSDLException(String message) { + super(message); + } + + public MissingWSDLException(String message, Throwable cause) { + super(message, cause); + } + + public MissingWSDLException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/NotSupportedWSDLException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/NotSupportedWSDLException.java new file mode 100644 index 0000000000..0d69d401f8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/NotSupportedWSDLException.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.idl.wsdl; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; + +/** + * An exception to indicate some WSDL styles that we don't support + */ +public class NotSupportedWSDLException extends InvalidServiceContractException { + + /** + * + */ + public NotSupportedWSDLException() { + } + + /** + * @param message + */ + public NotSupportedWSDLException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public NotSupportedWSDLException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param cause + */ + public NotSupportedWSDLException(Throwable cause) { + super(cause); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/UnresolveableResourceException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/UnresolveableResourceException.java new file mode 100644 index 0000000000..0454569e87 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/UnresolveableResourceException.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +/** + * @version $Rev$ $Date$ + */ +public class UnresolveableResourceException extends WSDLLoaderException { + public UnresolveableResourceException() { + } + + public UnresolveableResourceException(String message) { + super(message); + } + + public UnresolveableResourceException(String message, Throwable cause) { + super(message, cause); + } + + public UnresolveableResourceException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistry.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistry.java new file mode 100644 index 0000000000..0694811f0d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistry.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +import java.io.IOException; +import java.net.URL; +import javax.wsdl.Definition; +import javax.wsdl.PortType; +import javax.wsdl.Service; +import javax.wsdl.WSDLException; +import javax.wsdl.extensions.ExtensionRegistry; +import javax.xml.namespace.QName; + +/** + * A service for caching WSDLs + * + * @version $Rev$ $Date$ + */ +@Deprecated +public interface WSDLDefinitionRegistry { + /** + * Loads and registers a WSDL Definition. + * + * @param namespace the expected namespace, or null if any namespace should be allowed + * @param location the location to load the definition from + * @return the loaded Definition + * @throws IOException if there was a problem reading the document + * @throws WSDLException if there was a problem parsing the definition + */ + Definition loadDefinition(String namespace, URL location) throws IOException, WSDLException; + + /** + * Load and register a WSDL definition as specified in a WSDL2.0 wsdlLocation attribute. + * + * @param wsdlLocation the value of the wsdlLocation attribute + * @param classLoader application classloader used to support relative locations + * @return the loaded Definition + * @throws IOException if there was a problem reading the document + * @throws WSDLException if there was a problem parsing the definition + */ + Definition loadDefinition(String wsdlLocation, ClassLoader classLoader) throws IOException, WSDLException; + + /** + * Returns the PortType with the supplied qualified name, or null if no such port has been defined. + * + * @param name the qualified name of the WSDL portType + * @return the PortType for the supplied name, or null if none has been defined + */ + PortType getPortType(QName name); + + /** + * Returns the ServiceDefinition with the supplied qualified name, or null if no such service has been defined. + * + * @param name the qualified name of the WSDL service + * @return the ServiceDefinition for the supplied name, or null if none has been defined + */ + Service getService(QName name); + + + /** + * Returns the ExtensionRegistry that is used when parsing WSDL documents during the loadDefinition call. + * + * @return the ExtensionRegistry that is used when parsing WSDL documents. + */ + ExtensionRegistry getExtensionRegistry(); + + /** + * Get the XMLSchemaRegistry + * + * @return + */ + XMLSchemaRegistry getSchemaRegistry(); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistryImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistryImpl.java new file mode 100644 index 0000000000..976a09caca --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistryImpl.java @@ -0,0 +1,204 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.idl.wsdl; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.wsdl.Definition; +import javax.wsdl.Import; +import javax.wsdl.PortType; +import javax.wsdl.Service; +import javax.wsdl.WSDLException; +import javax.wsdl.extensions.ExtensionRegistry; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.annotation.Autowire; + +/** + * The default implementation of the runtime WSDL registry + * + * @version $Rev$ $Date$ + */ +public class WSDLDefinitionRegistryImpl implements WSDLDefinitionRegistry { + private final WSDLFactory wsdlFactory; + + private final ExtensionRegistry registry; + + private final Map<URL, Definition> definitionsByLocation = new HashMap<URL, Definition>(); + + private final Map<String, List<Definition>> definitionsByNamespace = new HashMap<String, List<Definition>>(); + + private Monitor monitor; + + private XMLSchemaRegistry schemaRegistry; + + public WSDLDefinitionRegistryImpl() throws WSDLException { + wsdlFactory = WSDLFactory.newInstance(); + registry = wsdlFactory.newPopulatedExtensionRegistry(); + } + + @Autowire + public void setSchemaRegistry(XMLSchemaRegistry schemaRegistry) { + this.schemaRegistry = schemaRegistry; + } + + @org.apache.tuscany.api.annotation.Monitor + public void setMonitor(Monitor monitor) { + this.monitor = monitor; + } + + public ExtensionRegistry getExtensionRegistry() { + return registry; + } + + public Definition loadDefinition(String wsdlLocation, ClassLoader classLoader) throws IOException, WSDLException { + int index = wsdlLocation.indexOf(' '); + if (index == -1) { + throw new WSDLException(WSDLException.CONFIGURATION_ERROR, "Invalid wsdlLocation: " + wsdlLocation); + } + String namespace = wsdlLocation.substring(0, index).trim(); + URL url; + URI uri; + try { + uri = new URI(wsdlLocation.substring(index + 1).trim()); + } catch (URISyntaxException e) { + throw new WSDLException(WSDLException.CONFIGURATION_ERROR, "Invalid wsdlLocation: " + wsdlLocation); + } + if (uri.isAbsolute()) { + url = uri.toURL(); + } else { + url = classLoader.getResource(uri.toString()); + if (url == null) { + throw new WSDLException(WSDLException.CONFIGURATION_ERROR, "Resource not found: " + uri); + } + } + return loadDefinition(namespace, url); + } + + public Definition loadDefinition(String namespace, URL location) throws IOException, WSDLException { + Definition definition = definitionsByLocation.get(location); + if (definition != null) { + // return cached copy + return definition; + } + + if (monitor != null) { + monitor.readingWSDL(namespace, location); + } + WSDLReader reader = wsdlFactory.newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + reader.setExtensionRegistry(registry); + + definition = reader.readWSDL(location.toString()); + String definitionNamespace = definition.getTargetNamespace(); + if (namespace != null && !namespace.equals(definitionNamespace)) { + throw new WSDLException(WSDLException.CONFIGURATION_ERROR, namespace + " != " + + definition.getTargetNamespace()); + } + + // Load inline schemas + getSchemaRegistry().loadSchemas(definition); + for (Object i : definition.getImports().values()) { + Import imp = (Import) i; + Definition imported = imp.getDefinition(); + if (imported != null) { + getSchemaRegistry().loadSchemas(imported); + } + } + + if (monitor != null) { + monitor.cachingDefinition(definitionNamespace, location); + } + definitionsByLocation.put(location, definition); + List<Definition> definitions = definitionsByNamespace.get(definitionNamespace); + if (definitions == null) { + definitions = new ArrayList<Definition>(); + definitionsByNamespace.put(definitionNamespace, definitions); + } + definitions.add(definition); + + return definition; + } + + public PortType getPortType(QName name) { + String namespace = name.getNamespaceURI(); + List<Definition> definitions = definitionsByNamespace.get(namespace); + if (definitions == null) { + return null; + } + for (Definition definition : definitions) { + PortType portType = definition.getPortType(name); + if (portType != null) { + return portType; + } + } + return null; + } + + public Service getService(QName name) { + String namespace = name.getNamespaceURI(); + List<Definition> definitions = definitionsByNamespace.get(namespace); + if (definitions == null) { + return null; + } + for (Definition definition : definitions) { + Service service = definition.getService(name); + if (service != null) { + return service; + } + } + return null; + } + + public static interface Monitor { + /** + * Monitor event emitted immediately before an attempt is made to read WSDL for the supplied namespace from the + * supplied location. + * + * @param namespace the target namespace expected in the WSDL; may be null + * @param location the location where we will attempt to read the WSDL definition from + */ + void readingWSDL(String namespace, URL location); + + /** + * Monitor event emitted immediately before registering a WSDL definition in the cache. + * + * @param namespace the target namespace for the WSDL + * @param location the location where the WSDL definition was read from + */ + void cachingDefinition(String namespace, URL location); + } + + public XMLSchemaRegistry getSchemaRegistry() { + if (schemaRegistry == null) { + // Default + schemaRegistry = new XMLSchemaRegistryImpl(); + } + return schemaRegistry; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoader.java new file mode 100644 index 0000000000..fb90e839f5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoader.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +import java.net.URI; +import java.util.Collection; +import javax.wsdl.Definition; +import javax.wsdl.PortType; +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; + +/** + * Interface for implementations that allow WSDL definitions to be loaded. Currently we do not have a complete solution + * for handling both WSDL2.0 and WSDL1.1 definitions so the current implementation only deals with loading WSDL1.1. This + * will change in the near future (for example when Woden supports both forms) so all WSDL1.1 specific methods are + * deprecated. + * + * @version $Rev$ $Date$ + */ +public interface WSDLLoader { + /** + * Load a WSDL 1.1 Definition for a namespace from one of specified locations. + * + * @param namespace the namespace whose definition should be loaded + * @param locations a set of possible locations to load from + * @return the loaded Definition + * @throws WSDLException if there was a problem loading the definition + */ + @Deprecated + Definition loadDefinition(String namespace, Collection<WSDLLocation> locations) + throws WSDLException, UnresolveableResourceException; + + /** + * Load a WSDL 1.1 Definition from the specified location + * + * @param location the location to load from + * @return the loaded Definition + * @throws WSDLException if there was a problem loading the definition + */ + @Deprecated + Definition loadDefinition(WSDLLocation location) throws WSDLException; + + /** + * Return the WSDL1.1 PortType for the specified interface IRI. + * + * @param interfaceIRI the WSDL2.0 interface IRI + * @param wsdlLocation the location of the WSDL instance + * @param base a Classloader from which to load + * @return the specified port type + */ + @Deprecated + PortType loadPortType(URI interfaceIRI, String wsdlLocation, ClassLoader base) + throws WSDLLoaderException, WSDLException; + + /** + * Parses a WSDL2.0 wsdlLocation attribute definition and returns a Collection of all locations it contains. + * + * @param wsdlLocation a list of namespace/location pairs as specified by WSDL2.0 + * @param base a ClassLoader to use to resolve relative URLs + * @return a collection of locations parsed from the string + * @throws InvalidWSDLLocationException + */ + Collection<WSDLLocation> getLocations(String wsdlLocation, ClassLoader base) throws InvalidWSDLLocationException; + + /** + * Returns the fully qualified name of a WSDL interface parsed from a IRI as defined by WSDL2.0. The value of the + * IRI defines the namespace, the fragment specifies the interface component; for example + * <code>http://example.org/TicketAgent.wsdl20#wsdl.interface(TicketAgent)</code> + * + * @param interfaceIRI the IRI for the interface + * @return the qualified name of the interface + * @throws UnresolveableResourceException if the URI is relative + * @throws InvalidFragmentException if the fragment is incorrectly formed + */ + QName getInterfaceName(URI interfaceIRI) throws UnresolveableResourceException, InvalidFragmentException; + + /** + * Returns an interface parsed from a wsdl.interface fragment. + * + * @param fragment the fragment value + * @return the interface name + * @throws InvalidFragmentException if the fragment is incorrectly formed + */ + String getInterfaceName(String fragment) throws InvalidFragmentException; + + /** + * Returns a namespace parsed from an IRI. This is the URI with any fragment removed. + * + * @param iri the IRI + * @return a namespace created by stripping fragment information from the URI + * @throws UnresolveableResourceException if the URI is relative + */ + String getNamespace(URI iri) throws UnresolveableResourceException; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoaderException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoaderException.java new file mode 100644 index 0000000000..47a4b8ef1f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoaderException.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +import org.apache.tuscany.api.TuscanyException; + +/** + * @version $Rev$ $Date$ + */ +public abstract class WSDLLoaderException extends TuscanyException { + protected WSDLLoaderException() { + } + + protected WSDLLoaderException(String message) { + super(message); + } + + protected WSDLLoaderException(String message, Throwable cause) { + super(message, cause); + } + + protected WSDLLoaderException(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoaderImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoaderImpl.java new file mode 100644 index 0000000000..cdf69fa1e8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLoaderImpl.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import javax.wsdl.Definition; +import javax.wsdl.PortType; +import javax.wsdl.WSDLException; +import javax.wsdl.extensions.ExtensionRegistry; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.namespace.QName; + +/** + * @version $Rev$ $Date$ + */ +public class WSDLLoaderImpl implements WSDLLoader { + private final WSDLFactory wsdlFactory; + + private final ExtensionRegistry registry; + + public WSDLLoaderImpl() throws WSDLException { + wsdlFactory = WSDLFactory.newInstance(); + registry = wsdlFactory.newPopulatedExtensionRegistry(); + } + + public PortType loadPortType(URI interfaceIRI, String wsdlLocation, ClassLoader base) + throws WSDLLoaderException, WSDLException { + Collection<WSDLLocation> locations = getLocations(wsdlLocation, base); + QName interfaceName = getInterfaceName(interfaceIRI); + + Definition definition = loadDefinition(interfaceName.getNamespaceURI(), locations); + return definition.getPortType(interfaceName); + } + + public Definition loadDefinition(String namespace, Collection<WSDLLocation> locations) + throws WSDLException, UnresolveableResourceException { + for (WSDLLocation location : locations) { + if (namespace.equals(location.getNamespace()) && location.getLocation() != null) { + return loadDefinition(location); + } + } + throw new UnresolveableResourceException(namespace); + } + + public Definition loadDefinition(WSDLLocation location) throws WSDLException { + String namespace = location.getNamespace(); + + WSDLReader reader = wsdlFactory.newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + reader.setExtensionRegistry(registry); + + Definition definition = reader.readWSDL(location.getLocation().toString()); + String definitionNamespace = definition.getTargetNamespace(); + if (namespace != null && !namespace.equals(definitionNamespace)) { + throw new WSDLException(WSDLException.CONFIGURATION_ERROR, namespace + " != " + + definition.getTargetNamespace()); + } + return definition; + } + + public Collection<WSDLLocation> getLocations(String wsdlLocation, ClassLoader base) + throws InvalidWSDLLocationException { + String parts[] = wsdlLocation.split("\\s"); + // check the number of parts is a multiple of two + if ((parts.length & 1) != 0) { + throw new InvalidWSDLLocationException(wsdlLocation); + } + List<WSDLLocation> locations = new ArrayList<WSDLLocation>(parts.length >>> 1); + for (int i = 0; i < parts.length; i += 2) { + URL url; + try { + URI uri = new URI(parts[i + 1]); + if (uri.isAbsolute()) { + url = uri.toURL(); + } else { + url = base.getResource(uri.toString()); + } + } catch (MalformedURLException e) { + throw new InvalidWSDLLocationException(e); + } catch (URISyntaxException e) { + throw new InvalidWSDLLocationException(e); + } + WSDLLocation location = new WSDLLocation(parts[i], url); + locations.add(location); + } + return locations; + } + + public QName getInterfaceName(URI interfaceIRI) throws UnresolveableResourceException, InvalidFragmentException { + String namespace = getNamespace(interfaceIRI); + String interfaceName = getInterfaceName(interfaceIRI.getFragment()); + return new QName(namespace, interfaceName); + } + + public String getInterfaceName(String fragment) throws InvalidFragmentException { + if (fragment == null) { + throw new InvalidFragmentException("missing fragment"); + } + String[] parts = fragment.split("\\s"); + for (String part : parts) { + if (part.startsWith("wsdl.interface(") && part.charAt(part.length() - 1) == ')') { + return part.substring(15, part.length() - 1); + } + } + throw new InvalidFragmentException(fragment); + } + + public String getNamespace(URI iri) throws UnresolveableResourceException { + if (!iri.isAbsolute()) { + UnresolveableResourceException ure = new UnresolveableResourceException("no namespace defined in " + iri); + ure.setIdentifier(iri.toString()); + throw ure; + } + StringBuilder s = new StringBuilder(); + s.append(iri.getScheme()); + s.append(':'); + s.append(iri.getSchemeSpecificPart()); + return s.toString(); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLocation.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLocation.java new file mode 100644 index 0000000000..a124294c3a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLLocation.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.idl.wsdl; + +import java.net.URL; + +/** + * A location where the WSDL for a namespace can be found. + * + * @version $Rev$ $Date$ + */ +public class WSDLLocation { + private final String namespace; + private final URL location; + + /** + * Constructor specifying a namespace and where its WSDL can be found. + * + * @param namespace the target namespace + * @param location the location of the WSDL + */ + public WSDLLocation(String namespace, URL location) { + this.namespace = namespace; + this.location = location; + } + + /** + * Returns the target namespace. + * + * @return the target namespace + */ + public String getNamespace() { + return namespace; + } + + /** + * Returns the location where the WSDL definition can be found. + * + * @return the location where the WSDL definition can be found + */ + public URL getLocation() { + return location; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLOperation.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLOperation.java new file mode 100644 index 0000000000..75fe1b9964 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLOperation.java @@ -0,0 +1,500 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.idl.wsdl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import javax.wsdl.Fault; +import javax.wsdl.Input; +import javax.wsdl.Message; +import javax.wsdl.Operation; +import javax.wsdl.Output; +import javax.wsdl.Part; +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.idl.ElementInfo; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.TypeInfo; +import org.apache.tuscany.spi.idl.WrapperInfo; +import org.apache.tuscany.spi.model.DataType; +import org.apache.ws.commons.schema.XmlSchemaComplexType; +import org.apache.ws.commons.schema.XmlSchemaElement; +import org.apache.ws.commons.schema.XmlSchemaObject; +import org.apache.ws.commons.schema.XmlSchemaObjectCollection; +import org.apache.ws.commons.schema.XmlSchemaParticle; +import org.apache.ws.commons.schema.XmlSchemaSequence; +import org.apache.ws.commons.schema.XmlSchemaSimpleType; +import org.apache.ws.commons.schema.XmlSchemaType; + +/** + * Metadata for a WSDL operation + */ +public class WSDLOperation { + private static final String OPERATION_KEY = org.apache.tuscany.spi.model.Operation.class.getName(); + + protected XMLSchemaRegistry schemaRegistry; + + protected Operation operation; + + private String dataBinding; + + protected org.apache.tuscany.spi.model.Operation<QName> operationModel; + + protected DataType<List<DataType<QName>>> inputType; + + protected DataType<QName> outputType; + + protected List<DataType<QName>> faultTypes; + + /** + * @param operation The WSDL4J operation + * @param dataBinding The default databinding + * @param schemaRegistry The XML Schema registry + */ + public WSDLOperation(Operation operation, String dataBinding, XMLSchemaRegistry schemaRegistry) { + super(); + this.operation = operation; + this.dataBinding = dataBinding; + this.schemaRegistry = schemaRegistry; + this.wrapper = new Wrapper(); + } + + private Wrapper wrapper; + + private Boolean wrapperStyle; + + /** + * Test if the operation qualifies wrapper style as defined by the JAX-WS 2.0 spec + * + * @return true if the operation qualifies wrapper style, otherwise false + */ + public boolean isWrapperStyle() { + if (wrapperStyle == null) { + wrapperStyle = + Boolean.valueOf(wrapper.getInputChildElements() != null + && (operation.getOutput() == null || wrapper.getOutputChildElements() != null)); + } + return wrapperStyle.booleanValue(); + } + + public Wrapper getWrapper() { + if (!isWrapperStyle()) { + throw new IllegalStateException("The operation is not wrapper style."); + } else { + return wrapper; + } + } + + /** + * @return + * @throws InvalidServiceContractException + */ + public DataType<List<DataType<QName>>> getInputType() throws InvalidServiceContractException { + if (inputType == null) { + Input input = operation.getInput(); + Message message = (input == null) ? null : input.getMessage(); + inputType = getMessageType(message); + inputType.setDataBinding("idl:input"); + } + return inputType; + } + + /** + * @return + * @throws NotSupportedWSDLException + */ + public DataType<QName> getOutputType() throws InvalidServiceContractException { + if (outputType == null) { + Output output = operation.getOutput(); + Message outputMsg = (output == null) ? null : output.getMessage(); + + List outputParts = (outputMsg == null) ? null : outputMsg.getOrderedParts(null); + if (outputParts != null && outputParts.size() > 0) { + if (outputParts.size() > 1) { + // We don't support output with multiple parts + throw new NotSupportedWSDLException("Multi-part output is not supported"); + } + Part part = (Part) outputParts.get(0); + outputType = new WSDLPart(part).getDataType(); + // outputType.setMetadata(WSDLOperation.class.getName(), this); + } + } + return outputType; + } + + /** + * @return + * @throws NotSupportedWSDLException + */ + public List<DataType<QName>> getFaultTypes() throws InvalidServiceContractException { + if (faultTypes == null) { + Collection faults = operation.getFaults().values(); + faultTypes = new ArrayList<DataType<QName>>(); + for (Object f : faults) { + Fault fault = (Fault) f; + Message faultMsg = fault.getMessage(); + List faultParts = faultMsg.getOrderedParts(null); + if (faultParts.size() != 1) { + throw new NotSupportedWSDLException("The fault message MUST have a single part"); + } + Part part = (Part) faultParts.get(0); + WSDLPart wsdlPart = new WSDLPart(part); + faultTypes.add(wsdlPart.getDataType()); + } + } + return faultTypes; + } + + private DataType<List<DataType<QName>>> getMessageType(Message message) throws InvalidServiceContractException { + List<DataType<QName>> partTypes = new ArrayList<DataType<QName>>(); + if (message != null) { + Collection parts = message.getOrderedParts(null); + for (Object p : parts) { + WSDLPart part = new WSDLPart((Part) p); + DataType<QName> partType = part.getDataType(); + partTypes.add(partType); + } + } + return new DataType<List<DataType<QName>>>(dataBinding, Object[].class, partTypes); + } + + /** + * @return + * @throws NotSupportedWSDLException + */ + public org.apache.tuscany.spi.model.Operation<QName> getOperation() throws InvalidServiceContractException { + if (operationModel == null) { + boolean oneway = (operation.getOutput() == null); + operationModel = + new org.apache.tuscany.spi.model.Operation<QName>(operation.getName(), getInputType(), + getOutputType(), getFaultTypes(), oneway, dataBinding); + operationModel.setWrapperStyle(isWrapperStyle()); + // operationModel.setMetaData(WSDLOperation.class.getName(), this); + if (isWrapperStyle()) { + operationModel.setWrapper(getWrapper().getWrapperInfo()); + // Register the operation with the types + for (DataType<?> d : wrapper.getUnwrappedInputType().getLogical()) { + d.setMetadata(OPERATION_KEY, operationModel); + } + if (wrapper.getUnwrappedOutputType() != null) { + wrapper.getUnwrappedOutputType().setMetadata(OPERATION_KEY, operationModel); + } + } + } + inputType.setMetadata(OPERATION_KEY, operationModel); + if (outputType != null) { + outputType.setMetadata(OPERATION_KEY, operationModel); + } + return operationModel; + } + + /** + * Metadata for a WSDL part + */ + public class WSDLPart { + private Part part; + + private XmlSchemaElement element; + + private DataType<QName> dataType; + + public WSDLPart(Part part) throws InvalidWSDLException { + this.part = part; + QName elementName = part.getElementName(); + if (elementName != null) { + element = schemaRegistry.getElement(elementName); + if (element == null) { + throw new InvalidWSDLException("Element cannot be resolved: " + elementName); + } + } else { + // Create an faked XSD element to host the metadata + element = new XmlSchemaElement(); + element.setName(part.getName()); + element.setQName(new QName(null, part.getName())); + QName typeName = part.getTypeName(); + if (typeName != null) { + XmlSchemaType type = schemaRegistry.getType(typeName); + if (type == null) { + throw new InvalidWSDLException("Type cannot be resolved: " + typeName); + } + element.setSchemaType(type); + element.setSchemaTypeName(type.getQName()); + } + } + dataType = new DataType<QName>(dataBinding, Object.class, element.getQName()); + // dataType.setMetadata(WSDLPart.class.getName(), this); + dataType.setMetadata(ElementInfo.class.getName(), getElementInfo(element)); + } + + /** + * @return the element + */ + public XmlSchemaElement getElement() { + return element; + } + + /** + * @return the part + */ + public Part getPart() { + return part; + } + + /** + * @return the dataType + */ + public DataType<QName> getDataType() { + return dataType; + } + } + + /** + * The "Wrapper Style" WSDL operation is defined by The Java API for XML-Based Web Services (JAX-WS) 2.0 + * specification, section 2.3.1.2 Wrapper Style. + * <p> + * A WSDL operation qualifies for wrapper style mapping only if the following criteria are met: + * <ul> + * <li>(i) The operation’s input and output messages (if present) each contain only a single part + * <li>(ii) The input message part refers to a global element declaration whose localname is equal to the operation + * name + * <li>(iii) The output message part refers to a global element declaration + * <li>(iv) The elements referred to by the input and output message parts (henceforth referred to as wrapper + * elements) are both complex types defined using the xsd:sequence compositor + * <li>(v) The wrapper elements only contain child elements, they must not contain other structures such as + * wildcards (element or attribute), xsd:choice, substitution groups (element references are not permitted) or + * attributes; furthermore, they must not be nillable. + * </ul> + */ + public class Wrapper { + private XmlSchemaElement inputWrapperElement; + + private XmlSchemaElement outputWrapperElement; + + private List<XmlSchemaElement> inputElements; + + private List<XmlSchemaElement> outputElements; + + private DataType<List<DataType<QName>>> unwrappedInputType; + + private DataType<QName> unwrappedOutputType; + + private transient WrapperInfo wrapperInfo; + + private List<XmlSchemaElement> getChildElements(XmlSchemaElement element) { + if (element == null) { + return null; + } + XmlSchemaType type = element.getSchemaType(); + if (!(type instanceof XmlSchemaComplexType)) { + // Has to be a complexType + return null; + } + XmlSchemaComplexType complexType = (XmlSchemaComplexType) type; + if (complexType.getAttributes().getCount() != 0 || complexType.getAnyAttribute() != null) { + // No attributes + return null; + } + XmlSchemaParticle particle = complexType.getParticle(); + if (particle == null) { + // No particle + return Collections.emptyList(); + } + if (!(particle instanceof XmlSchemaSequence)) { + return null; + } + XmlSchemaSequence sequence = (XmlSchemaSequence) complexType.getParticle(); + XmlSchemaObjectCollection items = sequence.getItems(); + List<XmlSchemaElement> childElements = new ArrayList<XmlSchemaElement>(); + for (int i = 0; i < items.getCount(); i++) { + XmlSchemaObject schemaObject = items.getItem(i); + if (!(schemaObject instanceof XmlSchemaElement)) { + return null; + } + XmlSchemaElement childElement = (XmlSchemaElement) schemaObject; + if (childElement.getName() == null || childElement.getRefName() != null || childElement.isNillable()) { + return null; + } + // TODO: Do we support maxOccurs >1 ? + if (childElement.getMaxOccurs() > 1) { + return null; + } + childElements.add(childElement); + } + return childElements; + } + + /** + * Return a list of child XSD elements under the wrapped request element + * + * @return a list of child XSD elements or null if if the request element is not wrapped + */ + public List<XmlSchemaElement> getInputChildElements() { + if (inputElements != null) { + return inputElements; + } + Input input = operation.getInput(); + if (input != null) { + Message inputMsg = input.getMessage(); + Collection parts = inputMsg.getParts().values(); + if (parts.size() != 1) { + return null; + } + Part part = (Part) parts.iterator().next(); + QName elementName = part.getElementName(); + if (elementName == null) { + return null; + } + if (!operation.getName().equals(elementName.getLocalPart())) { + return null; + } + inputWrapperElement = schemaRegistry.getElement(elementName); + if (inputWrapperElement == null) { + return null; + } + inputElements = getChildElements(inputWrapperElement); + return inputElements; + } else { + return null; + } + } + + /** + * Return a list of child XSD elements under the wrapped response element + * + * @return a list of child XSD elements or null if if the response element is not wrapped + */ + public List<XmlSchemaElement> getOutputChildElements() { + if (outputElements != null) { + return outputElements; + } + Output output = operation.getOutput(); + if (output != null) { + Message outputMsg = output.getMessage(); + Collection parts = outputMsg.getParts().values(); + if (parts.size() != 1) { + return null; + } + Part part = (Part) parts.iterator().next(); + QName elementName = part.getElementName(); + if (elementName == null) { + return null; + } + outputWrapperElement = schemaRegistry.getElement(elementName); + if (outputWrapperElement == null) { + return null; + } + outputElements = getChildElements(outputWrapperElement); + // FIXME: Do we support multiple child elements for the response? + return outputElements; + } else { + return null; + } + } + + /** + * @return the inputWrapperElement + */ + public XmlSchemaElement getInputWrapperElement() { + return inputWrapperElement; + } + + /** + * @return the outputWrapperElement + */ + public XmlSchemaElement getOutputWrapperElement() { + return outputWrapperElement; + } + + public DataType<List<DataType<QName>>> getUnwrappedInputType() { + if (unwrappedInputType == null) { + List<DataType<QName>> childTypes = new ArrayList<DataType<QName>>(); + for (XmlSchemaElement element : getInputChildElements()) { + DataType<QName> type = new DataType<QName>(dataBinding, Object.class, element.getQName()); + type.setMetadata(ElementInfo.class.getName(), getElementInfo(element)); + childTypes.add(type); + } + unwrappedInputType = + new DataType<List<DataType<QName>>>("idl:unwrapped.input", Object[].class, childTypes); + } + return unwrappedInputType; + } + + public DataType<QName> getUnwrappedOutputType() throws InvalidServiceContractException { + if (unwrappedOutputType == null) { + List<XmlSchemaElement> elements = getOutputChildElements(); + if (elements != null && elements.size() > 0) { + if (elements.size() > 1) { + // We don't support output with multiple parts + throw new NotSupportedWSDLException("Multi-part output is not supported"); + } + XmlSchemaElement element = elements.get(0); + unwrappedOutputType = new DataType<QName>(dataBinding, Object.class, element.getQName()); + unwrappedOutputType.setMetadata(ElementInfo.class.getName(), getElementInfo(element)); + } + } + return unwrappedOutputType; + } + + public WrapperInfo getWrapperInfo() throws InvalidServiceContractException { + if (wrapperInfo == null) { + ElementInfo in = getElementInfo(getInputWrapperElement()); + ElementInfo out = getElementInfo(getOutputWrapperElement()); + List<ElementInfo> inChildren = new ArrayList<ElementInfo>(); + for (XmlSchemaElement e : getInputChildElements()) { + inChildren.add(getElementInfo(e)); + } + List<ElementInfo> outChildren = new ArrayList<ElementInfo>(); + if (out != null) { + for (XmlSchemaElement e : getOutputChildElements()) { + outChildren.add(getElementInfo(e)); + } + } + wrapperInfo = + new WrapperInfo(in, out, inChildren, outChildren, getUnwrappedInputType(), getUnwrappedOutputType()); + } + return wrapperInfo; + } + } + + private static ElementInfo getElementInfo(XmlSchemaElement element) { + if (element == null) { + return null; + } + return new ElementInfo(element.getQName(), getTypeInfo(element.getSchemaType())); + } + + private static TypeInfo getTypeInfo(XmlSchemaType type) { + if (type == null) { + return null; + } + XmlSchemaType baseType = (XmlSchemaType) type.getBaseSchemaType(); + QName name = type.getQName(); + boolean simple = (type instanceof XmlSchemaSimpleType); + if (baseType == null) { + return new TypeInfo(name, simple, null); + } else { + return new TypeInfo(name, simple, getTypeInfo(baseType)); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLServiceContract.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLServiceContract.java new file mode 100644 index 0000000000..868ad0f3b4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/WSDLServiceContract.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.idl.wsdl; + +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import org.apache.tuscany.spi.model.ServiceContract; + +/** + * Represents a service contract specified by a WSDL + * + * @version $Rev$ $Date$ + */ +public class WSDLServiceContract extends ServiceContract<QName> { + private PortType portType; + private PortType callbackPortType; + + /** + * + */ + public WSDLServiceContract() { + super(); + this.remotable = true; // WSDL interface is always remotable by the SCA spec + } + + + public PortType getPortType() { + return portType; + } + + public void setPortType(PortType portType) { + this.portType = portType; + } + + public PortType getCallbackPortType() { + return callbackPortType; + } + + public void setCallbackPortType(PortType callbackPortType) { + this.callbackPortType = callbackPortType; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistry.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistry.java new file mode 100644 index 0000000000..681e08be4d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistry.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.idl.wsdl; + +import java.io.IOException; +import java.net.URL; +import java.util.List; + +import javax.wsdl.Definition; +import javax.xml.namespace.QName; + +import org.apache.ws.commons.schema.XmlSchema; +import org.apache.ws.commons.schema.XmlSchemaElement; +import org.apache.ws.commons.schema.XmlSchemaException; +import org.apache.ws.commons.schema.XmlSchemaType; + +/** + * A service for caching XML Schemas + * + * @version $Rev$ $Date$ + */ +public interface XMLSchemaRegistry { + /** + * Load all inline schemas from the WSDL definition + * + * @param definition The WSDL defintion whose types element contains a list of schemas + * @return A list of inline schemas + */ + List<XmlSchema> loadSchemas(Definition definition); + + /** + * Loads and registers a XML schema. + * + * @param namespace the expected namespace, or null if any namespace should be allowed + * @param location the location to load the schema from + * @return the loaded Definition + * @throws IOException if there was a problem reading the document + * @throws XmlSchemaException if there was a problem parsing the schema + */ + XmlSchema loadSchema(String namespace, URL location) throws IOException, XmlSchemaException; + + /** + * Load and register a XML schema as specified in a XSD schemaLocation attribute. + * + * @param schemaLocation the value of the schemaLocation attribute + * @param classLoader application classloader used to support relative locations + * @return the loaded schema + * @throws IOException if there was a problem reading the document + * @throws XmlSchemaException if there was a problem parsing the schema + */ + XmlSchema loadSchema(String schemaLocation, ClassLoader classLoader) throws IOException, XmlSchemaException; + + /** + * Returns the XSD Element with the supplied qualified name, or null if no such element has been defined. + * + * @param name the qualified name of the XSD element + * @return the XSD element for the supplied name, or null if none has been defined + */ + XmlSchemaElement getElement(QName name); + + /** + * Returns the XmlSchemaType with the supplied qualified name, or null if no such type has been defined. + * + * @param name the qualified name of the XSD type + * @return the XSD type for the supplied name, or null if none has been defined + */ + XmlSchemaType getType(QName name); + + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistryImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistryImpl.java new file mode 100644 index 0000000000..08600e4b7e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistryImpl.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.idl.wsdl; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.wsdl.Definition; +import javax.wsdl.Types; +import javax.wsdl.extensions.schema.Schema; +import javax.xml.namespace.QName; + +import org.apache.ws.commons.schema.XmlSchema; +import org.apache.ws.commons.schema.XmlSchemaCollection; +import org.apache.ws.commons.schema.XmlSchemaElement; +import org.apache.ws.commons.schema.XmlSchemaException; +import org.apache.ws.commons.schema.XmlSchemaType; +import org.osoa.sca.annotations.Service; +import org.w3c.dom.Element; + +/** + * Default implementation of XMLSchemaRegistry + */ +@Service(XMLSchemaRegistry.class) +public class XMLSchemaRegistryImpl implements XMLSchemaRegistry { + private final XmlSchemaCollection collection; + + /** + * @param collection + */ + public XMLSchemaRegistryImpl(XmlSchemaCollection collection) { + super(); + this.collection = collection; + } + + public XMLSchemaRegistryImpl() { + super(); + this.collection = new XmlSchemaCollection(); + } + + public XmlSchemaElement getElement(QName name) { + return collection.getElementByQName(name); + } + + public XmlSchemaType getType(QName name) { + return collection.getTypeByQName(name); + } + + public List<XmlSchema> loadSchemas(Definition definition) { + Types types = definition.getTypes(); + if (types == null) { + return Collections.emptyList(); + } + List<XmlSchema> schemas = new ArrayList<XmlSchema>(); + for (Object ext : types.getExtensibilityElements()) { + if (ext instanceof Schema) { + Element element = ((Schema) ext).getElement(); + XmlSchema s = collection.read(element, element.getBaseURI()); + schemas.add(s); + } + } + return schemas; + } + + public XmlSchema loadSchema(String namespace, URL location) throws IOException, XmlSchemaException { + XmlSchema schema; + XmlSchema[] schemaList = collection.getXmlSchema(location.toExternalForm()); + if (schemaList != null && schemaList.length > 0) { + schema = schemaList[0]; + } else { + InputStream is = location.openStream(); + schema = collection.read(new InputStreamReader(is), null); + is.close(); + } + if (namespace != null && schema != null && !namespace.equals(schema.getTargetNamespace())) { + throw new XmlSchemaException(namespace + " != " + schema.getTargetNamespace()); + } + return schema; + } + + public XmlSchema loadSchema(String schemaLocation, ClassLoader classLoader) throws IOException, XmlSchemaException { + int index = schemaLocation.indexOf(' '); + if (index == -1) { + throw new XmlSchemaException("Invalid schemaLocation: " + schemaLocation); + } + String namespace = schemaLocation.substring(0, index).trim(); + URL url; + URI uri; + try { + uri = new URI(schemaLocation.substring(index + 1).trim()); + } catch (URISyntaxException e) { + throw new XmlSchemaException("Invalid schemaLocation: " + schemaLocation); + } + if (uri.isAbsolute()) { + url = uri.toURL(); + } else { + url = classLoader.getResource(uri.toString()); + if (url == null) { + throw new XmlSchemaException("Resource cannot be resolved: schemaLocation: " + schemaLocation); + } + } + return loadSchema(namespace, url); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/resources/META-INF/sca/default.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/resources/META-INF/sca/default.scdl new file mode 100644 index 0000000000..142df15171 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/resources/META-INF/sca/default.scdl @@ -0,0 +1,50 @@ +<?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.
+-->
+<!--
+ IDL WSDL extension
+
+ $Rev: 440894 $ $Date: 2006-09-06 15:52:01 -0700 (Wed, 06 Sep 2006) $
+-->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.idl.wsdl">
+
+ <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2">
+ <group>org.apache.tuscany.sca.services.idl</group>
+ <name>wsdl</name>
+ <version>1.0-incubator-M2-SNAPSHOT</version>
+ </dependency>
+
+ <component name="interface.wsdl.Loader">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.InterfaceWSDLLoader" />
+ </component>
+
+ <component name="wsdl.Registry">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistryImpl" initLevel="40" />
+ </component>
+
+ <component name="xmlSchema.registry">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.XMLSchemaRegistryImpl" initLevel="35" />
+ </component>
+
+ <component name="interface.wsdl.Introspector">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.InterfaceWSDLIntrospectorImpl" initLevel="40" />
+ </component>
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/resources/META-INF/sca/idl.wsdl.scdl b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/resources/META-INF/sca/idl.wsdl.scdl new file mode 100644 index 0000000000..28b3458bf1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/main/resources/META-INF/sca/idl.wsdl.scdl @@ -0,0 +1,52 @@ +<?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.
+-->
+<!--
+ IDL WSDL extension
+
+ This is a copy to be included by other extensions
+
+ $Rev: 440894 $ $Date: 2006-09-06 15:52:01 -0700 (Wed, 06 Sep 2006) $
+-->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" xmlns:system="http://incubator.apache.org/tuscany/xmlns/system/1.0-incubator-M2"
+ name="org.apache.tuscany.idl.wsdl.include">
+
+ <dependency xmlns="http://incubator.apache.org/tuscany/xmlns/1.0-incubator-M2">
+ <group>org.apache.tuscany.sca.services.idl</group>
+ <name>wsdl</name>
+ <version>1.0-incubator-M2-SNAPSHOT</version>
+ </dependency>
+
+ <component name="interface.wsdl.Loader">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.InterfaceWSDLLoader" />
+ </component>
+
+ <component name="wsdl.Registry">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.WSDLDefinitionRegistryImpl" initLevel="40" />
+ </component>
+
+ <component name="xmlSchema.registry">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.XMLSchemaRegistryImpl" initLevel="35" />
+ </component>
+
+ <component name="interface.wsdl.Introspector">
+ <system:implementation.system class="org.apache.tuscany.idl.wsdl.InterfaceWSDLIntrospectorImpl" initLevel="40" />
+ </component>
+
+</composite>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospectorImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospectorImplTestCase.java new file mode 100644 index 0000000000..8f263607e0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/InterfaceWSDLIntrospectorImplTestCase.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.idl.wsdl; + +import java.net.URL; +import java.util.List; +import java.util.Map; + +import javax.wsdl.Definition; +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.model.DataType; +import org.apache.tuscany.spi.model.Operation; + +/** + * Test case for InterfaceWSDLIntrospectorImpl + */ +public class InterfaceWSDLIntrospectorImplTestCase extends TestCase { + private static final QName PORTTYPE_NAME = new QName("http://example.com/stockquote.wsdl", "StockQuotePortType"); + + private WSDLDefinitionRegistryImpl registry; + private PortType portType; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + registry = new WSDLDefinitionRegistryImpl(); + registry.setSchemaRegistry(new XMLSchemaRegistryImpl()); + URL url = getClass().getResource("stockquote.wsdl"); + Definition definition = registry.loadDefinition(null, url); + portType = definition.getPortType(PORTTYPE_NAME); + } + + public final void testIntrospectPortType() throws InvalidServiceContractException { + InterfaceWSDLIntrospector introspector = new InterfaceWSDLIntrospectorImpl(registry); + WSDLServiceContract contract = introspector.introspect(portType); + Assert.assertEquals(contract.getInterfaceName(), "StockQuotePortType"); + Map<String, Operation<QName>> operations = contract.getOperations(); + Assert.assertEquals(1, operations.size()); + Operation<QName> operation = operations.get("getLastTradePrice"); + Assert.assertNotNull(operation); + DataType<List<DataType<QName>>> inputType = operation.getInputType(); + Assert.assertEquals(1, inputType.getLogical().size()); + DataType<QName> returnType = operation.getOutputType(); + Assert.assertNotNull(returnType); + Assert.assertEquals(0, operation.getFaultTypes().size()); + Assert.assertEquals(1, operation.getWrapper().getInputChildElements().size()); + Assert.assertEquals(1, operation.getWrapper().getOutputChildElements().size()); + } + + public final void testIntrospectPortTypePortType() throws InvalidServiceContractException { + InterfaceWSDLIntrospector introspector = new InterfaceWSDLIntrospectorImpl(registry); + WSDLServiceContract contract = introspector.introspect(portType, portType); + Assert.assertEquals("StockQuotePortType", contract.getInterfaceName()); + Assert.assertEquals("StockQuotePortType", contract.getCallbackName()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistryTestCase.java new file mode 100644 index 0000000000..a7d7457f76 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLDefinitionRegistryTestCase.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.idl.wsdl; + +import java.io.IOException; +import java.net.URL; +import javax.wsdl.Definition; +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; + +import junit.framework.TestCase; +import junit.framework.Assert; + +/** + * Verifies the default WSDL registry implementation + * + * @version $Rev$ $Date$ + */ +public class WSDLDefinitionRegistryTestCase extends TestCase { + private static final String NS = "http://www.example.org"; + private static final WSDLDefinitionRegistryImpl.Monitor NULL_MONITOR = new WSDLDefinitionRegistryImpl.Monitor() { + public void readingWSDL(String namespace, URL location) { + } + + public void cachingDefinition(String namespace, URL location) { + } + }; + private WSDLDefinitionRegistryImpl wsdlRegistry; + private ClassLoader cl; + private URL exampleWsdl; + + + public void testLoadFromAbsoluteWSDLLocation() { + try { + Definition def = wsdlRegistry.loadDefinition(NS + ' ' + exampleWsdl, cl); + Assert.assertNotNull(def.getPortType(new QName(NS, "HelloWorld"))); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } catch (WSDLException e) { + Assert.fail(e.getMessage()); + } + } + + public void testLoadFromRelativeWSDLLocation() { + try { + Definition def = wsdlRegistry.loadDefinition(NS + " org/apache/tuscany/idl/wsdl/example.wsdl", cl); + Assert.assertNotNull(def.getPortType(new QName(NS, "HelloWorld"))); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } catch (WSDLException e) { + Assert.fail(e.getMessage()); + } + } + + protected void setUp() throws Exception { + super.setUp(); + wsdlRegistry = new WSDLDefinitionRegistryImpl(); + wsdlRegistry.setSchemaRegistry(new XMLSchemaRegistryImpl()); + wsdlRegistry.setMonitor(NULL_MONITOR); + exampleWsdl = getClass().getResource("example.wsdl"); + cl = getClass().getClassLoader(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLLoaderImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLLoaderImplTestCase.java new file mode 100644 index 0000000000..c05cf9770f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLLoaderImplTestCase.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.idl.wsdl; + +import java.net.URI; + +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class WSDLLoaderImplTestCase extends TestCase { + private WSDLLoaderImpl loader; + private URI exampleURI; + private QName exampleName; + + public void testGetNamespace() throws UnresolveableResourceException { + assertEquals("http://example.org/TicketAgent.wsdl20", loader.getNamespace(exampleURI)); + } + + public void testGetInterfaceNameFromFragment() throws UnresolveableResourceException, InvalidFragmentException { + assertEquals("TicketAgent", loader.getInterfaceName("wsdl.interface(TicketAgent)")); + } + + public void testGetInterfaceNameFromURI() throws UnresolveableResourceException, InvalidFragmentException { + assertEquals(exampleName, loader.getInterfaceName(exampleURI)); + } + + protected void setUp() throws Exception { + super.setUp(); + loader = new WSDLLoaderImpl(); + exampleURI = URI.create("http://example.org/TicketAgent.wsdl20#wsdl.interface(TicketAgent)"); + exampleName = new QName("http://example.org/TicketAgent.wsdl20", "TicketAgent"); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLOperationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLOperationTestCase.java new file mode 100644 index 0000000000..b77e88d408 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WSDLOperationTestCase.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.idl.wsdl; + +import java.net.URL; +import java.util.List; + +import javax.wsdl.Definition; +import javax.wsdl.Operation; +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.spi.idl.ElementInfo; +import org.apache.tuscany.spi.model.DataType; + +/** + * Test case for WSDLOperation + */ +public class WSDLOperationTestCase extends TestCase { + private static final QName PORTTYPE_NAME = new QName("http://example.com/stockquote.wsdl", "StockQuotePortType"); + + private WSDLDefinitionRegistryImpl registry; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + registry = new WSDLDefinitionRegistryImpl(); + registry.setSchemaRegistry(new XMLSchemaRegistryImpl()); + } + + public final void testWrappedOperation() throws Exception { + URL url = getClass().getResource("stockquote.wsdl"); + Definition definition = registry.loadDefinition(null, url); + PortType portType = definition.getPortType(PORTTYPE_NAME); + Operation operation = portType.getOperation("getLastTradePrice", null, null); + + WSDLOperation op = new WSDLOperation(operation, "org.w3c.dom.Node", registry.getSchemaRegistry()); + + DataType<List<DataType<QName>>> inputType = op.getInputType(); + Assert.assertEquals(1, inputType.getLogical().size()); + Assert.assertEquals(new QName("http://example.com/stockquote.xsd", "getLastTradePrice"), inputType.getLogical() + .get(0).getLogical()); + + DataType<QName> outputType = op.getOutputType(); + Assert.assertEquals(new QName("http://example.com/stockquote.xsd", "getLastTradePriceResponse"), outputType + .getLogical()); + Assert.assertTrue(op.isWrapperStyle()); + + DataType<List<DataType<QName>>> unwrappedInputType = op.getWrapper().getUnwrappedInputType(); + List<DataType<QName>> childTypes = unwrappedInputType.getLogical(); + Assert.assertEquals(1, childTypes.size()); + DataType<QName> childType = childTypes.get(0); + Assert.assertEquals(new QName(null, "tickerSymbol"), childType.getLogical()); + ElementInfo element = (ElementInfo) childType.getMetadata(ElementInfo.class.getName()); + Assert.assertNotNull(element); + + childType = op.getWrapper().getUnwrappedOutputType(); + Assert.assertEquals(new QName(null, "price"), childType.getLogical()); + element = (ElementInfo) childType.getMetadata(ElementInfo.class.getName()); + Assert.assertNotNull(element); + } + + public final void testUnwrappedOperation() throws Exception { + URL url = getClass().getResource("unwrapped-stockquote.wsdl"); + Definition definition = registry.loadDefinition(null, url); + PortType portType = definition.getPortType(PORTTYPE_NAME); + + Operation operation = portType.getOperation("getLastTradePrice1", null, null); + WSDLOperation op = new WSDLOperation(operation, "org.w3c.dom.Node", registry.getSchemaRegistry()); + Assert.assertFalse(op.isWrapperStyle()); + Assert.assertEquals(1, op.getInputType().getLogical().size()); + + operation = portType.getOperation("getLastTradePrice2", null, null); + op = new WSDLOperation(operation, "org.w3c.dom.Node", registry.getSchemaRegistry()); + Assert.assertFalse(op.isWrapperStyle()); + Assert.assertEquals(2, op.getInputType().getLogical().size()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WrapperStyleOperationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WrapperStyleOperationTestCase.java new file mode 100644 index 0000000000..748c790297 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/WrapperStyleOperationTestCase.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.idl.wsdl; + +import java.net.URL; + +import javax.wsdl.Definition; +import javax.wsdl.Operation; +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import junit.framework.Assert; +import junit.framework.TestCase; + +/** + * Test case for WSDLOperation + */ +public class WrapperStyleOperationTestCase extends TestCase { + private static final QName PORTTYPE_NAME = new QName("http://example.com/stockquote.wsdl", "StockQuotePortType"); + + private WSDLDefinitionRegistryImpl registry; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + registry = new WSDLDefinitionRegistryImpl(); + registry.setSchemaRegistry(new XMLSchemaRegistryImpl()); + } + + public final void testWrappedOperation() throws Exception { + URL url = getClass().getResource("stockquote.wsdl"); + Definition definition = registry.loadDefinition(null, url); + PortType portType = definition.getPortType(PORTTYPE_NAME); + Operation operation = portType.getOperation("getLastTradePrice", null, null); + WSDLOperation op = new WSDLOperation(operation, "org.w3c.dom.Node", registry.getSchemaRegistry()); + Assert.assertTrue(op.isWrapperStyle()); + Assert.assertEquals(1, op.getWrapper().getInputChildElements().size()); + Assert.assertEquals(1, op.getWrapper().getOutputChildElements().size()); + } + + public final void testUnwrappedOperation() throws Exception { + URL url = getClass().getResource("unwrapped-stockquote.wsdl"); + Definition definition = registry.loadDefinition(null, url); + PortType portType = definition.getPortType(PORTTYPE_NAME); + Operation operation = portType.getOperation("getLastTradePrice1", null, null); + WSDLOperation op = new WSDLOperation(operation, "org.w3c.dom.Node", registry.getSchemaRegistry()); + Assert.assertFalse(op.isWrapperStyle()); + operation = portType.getOperation("getLastTradePrice2", null, null); + op = new WSDLOperation(operation, "org.w3c.dom.Node", registry.getSchemaRegistry()); + Assert.assertFalse(op.isWrapperStyle()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistryImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistryImplTestCase.java new file mode 100644 index 0000000000..60433d3bc1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/java/org/apache/tuscany/idl/wsdl/XMLSchemaRegistryImplTestCase.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.idl.wsdl; + +import java.io.IOException; +import java.net.URL; +import java.util.List; + +import javax.wsdl.Definition; +import javax.xml.namespace.QName; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.ws.commons.schema.XmlSchema; +import org.apache.ws.commons.schema.XmlSchemaComplexType; +import org.apache.ws.commons.schema.XmlSchemaElement; +import org.apache.ws.commons.schema.XmlSchemaException; +import org.apache.ws.commons.schema.XmlSchemaObjectCollection; +import org.apache.ws.commons.schema.XmlSchemaSequence; +import org.apache.ws.commons.schema.XmlSchemaType; + +/** + * Verifies the default XSD registry implementation + * + * @version $Rev$ $Date$ + */ +public class XMLSchemaRegistryImplTestCase extends TestCase { + private static final QName PO_ELEMENT_NAME = new QName("http://www.example.com/IPO", "purchaseOrder"); + private static final QName PO_TYPE_NAME = new QName("http://www.example.com/IPO", "PurchaseOrderType"); + + private static final String NS = "http://example.com/stockquote.xsd"; + private static final QName GET_LAST_TRADE_PRICE_ELEMENT_NAME = new QName(NS, "getLastTradePrice"); + + private XMLSchemaRegistryImpl xsdRegistry; + + private WSDLDefinitionRegistryImpl wsdlRegistry; + + private ClassLoader cl; + + private URL wsdl; + + public void testLoadFromAbsoluteWSDLLocation() { + try { + Definition definition = wsdlRegistry.loadDefinition(null, wsdl); + List<XmlSchema> schemas = xsdRegistry.loadSchemas(definition); + Assert.assertTrue(schemas.size() == 1); + XmlSchema schema = schemas.get(0); + XmlSchemaElement element = schema.getElementByName(GET_LAST_TRADE_PRICE_ELEMENT_NAME); + Assert.assertNotNull(element); + XmlSchemaType type = element.getSchemaType(); + XmlSchemaComplexType complexType = (XmlSchemaComplexType) type; + XmlSchemaSequence sequence = (XmlSchemaSequence) complexType.getParticle(); + XmlSchemaObjectCollection items = sequence.getItems(); + Assert.assertTrue(items.getItem(0) instanceof XmlSchemaElement); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + } + + public void testSchemaLocation() throws IOException { + String schemaLocation = "http://www.example.com/IPO org/apache/tuscany/idl/wsdl/ipo.xsd"; + XmlSchema schema = xsdRegistry.loadSchema(schemaLocation, cl); + Assert.assertNotNull(schema); + Assert.assertNotNull(schema.getElementByName(PO_ELEMENT_NAME)); + Assert.assertNotNull(xsdRegistry.getElement(PO_ELEMENT_NAME)); + Assert.assertNotNull(schema.getTypeByName(PO_TYPE_NAME)); + Assert.assertNotNull(xsdRegistry.getType(PO_TYPE_NAME)); + + + schemaLocation = "http://www.example.com/IPO1 org/apache/tuscany/idl/wsdl/ipo.xsd"; + try { + schema = xsdRegistry.loadSchema(schemaLocation, cl); + Assert.fail(""); + } catch (XmlSchemaException e) { + Assert.assertTrue(e.getMessage().contains("http://www.example.com/IPO1 !=")); + } + } + + protected void setUp() throws Exception { + super.setUp(); + xsdRegistry = new XMLSchemaRegistryImpl(); + wsdlRegistry = new WSDLDefinitionRegistryImpl(); + wsdlRegistry.setSchemaRegistry(xsdRegistry); + wsdl = getClass().getResource("stockquote.wsdl"); + cl = getClass().getClassLoader(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/example.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/example.wsdl new file mode 100644 index 0000000000..5e8e5dad0d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/example.wsdl @@ -0,0 +1,26 @@ +<?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. +--> +<wsdl:definitions targetNamespace="http://www.example.org" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + name="example"> + + <wsdl:portType name="HelloWorld"> + </wsdl:portType> +</wsdl:definitions> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/ipo.xsd b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/ipo.xsd new file mode 100644 index 0000000000..241ec15d36 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/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-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/stockquote.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/stockquote.wsdl new file mode 100644 index 0000000000..78e6bfe785 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/stockquote.wsdl @@ -0,0 +1,58 @@ +<?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/stockquote.wsdl"
+ xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd1="http://example.com/stockquote.xsd"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+ <types>
+ <schema targetNamespace="http://example.com/stockquote.xsd" xmlns="http://www.w3.org/2001/XMLSchema">
+ <element name="getLastTradePrice">
+ <complexType>
+ <sequence>
+ <element name="tickerSymbol" type="string" />
+ </sequence>
+ </complexType>
+ </element>
+ <element name="getLastTradePriceResponse">
+ <complexType>
+ <sequence>
+ <element name="price" type="float" />
+ </sequence>
+ </complexType>
+ </element>
+ </schema>
+ </types>
+
+ <message name="GetLastTradePriceInput">
+ <part name="body" element="xsd1:getLastTradePrice" />
+ </message>
+
+ <message name="GetLastTradePriceOutput">
+ <part name="body" element="xsd1:getLastTradePriceResponse" />
+ </message>
+
+ <portType name="StockQuotePortType">
+ <operation name="getLastTradePrice">
+ <input message="tns:GetLastTradePriceInput" />
+ <output message="tns:GetLastTradePriceOutput" />
+ </operation>
+ </portType>
+
+</definitions>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/unwrapped-stockquote.wsdl b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/unwrapped-stockquote.wsdl new file mode 100644 index 0000000000..c74c0c9b64 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/idl/wsdl/src/test/resources/org/apache/tuscany/idl/wsdl/unwrapped-stockquote.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/stockquote.wsdl"
+ xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd1="http://example.com/stockquote.xsd"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+ <types>
+ <schema targetNamespace="http://example.com/stockquote.xsd" xmlns="http://www.w3.org/2001/XMLSchema">
+ <element name="getLastTradePrice">
+ <complexType>
+ <sequence>
+ <element name="tickerSymbol" type="string" />
+ </sequence>
+ </complexType>
+ </element>
+ <element name="getLastTradePriceResponse">
+ <complexType>
+ <sequence>
+ <element name="price" type="float" />
+ </sequence>
+ </complexType>
+ </element>
+ </schema>
+ </types>
+
+ <message name="GetLastTradePriceInput1">
+ <part name="body" element="xsd1:getLastTradePrice" />
+ </message>
+
+ <message name="GetLastTradePriceOutput1">
+ <part name="body" element="xsd1:getLastTradePriceResponse" />
+ </message>
+
+ <message name="GetLastTradePriceInput2">
+ <part name="body" element="xsd1:getLastTradePrice" />
+ <part name="other" type="xsd:string"/>
+ </message>
+
+ <message name="GetLastTradePriceOutput2">
+ <part name="body" element="xsd1:getLastTradePriceResponse" />
+ </message>
+
+ <portType name="StockQuotePortType">
+ <operation name="getLastTradePrice">
+ <input message="tns:GetLastTradePriceInput1" />
+ <output message="tns:GetLastTradePriceOutput1" />
+ </operation>
+ <operation name="getLastTradePrice1">
+ <input message="tns:GetLastTradePriceInput1" />
+ <output message="tns:GetLastTradePriceOutput1" />
+ </operation>
+ <operation name="getLastTradePrice2">
+ <input message="tns:GetLastTradePriceInput2" />
+ <output message="tns:GetLastTradePriceOutput2" />
+ </operation>
+ </portType>
+
+</definitions>
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/LICENSE.txt new file mode 100644 index 0000000000..75b52484ea --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/LICENSE.txt @@ -0,0 +1,202 @@ +
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/NOTICE.txt new file mode 100644 index 0000000000..ecc68a9614 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name}
+Copyright (c) 2005 - 2006 The Apache Software Foundation
+
+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.
+
+This product includes software developed by
+The Apache Software Foundation (http://www.apache.org/).
+
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/pom.xml new file mode 100644 index 0000000000..685d1a0af0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/pom.xml @@ -0,0 +1,59 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>maven</artifactId> + <name>Apache Tuscany Maven Service</name> + <description>Tuscany Maven Service</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-api</artifactId> + <version>${pom.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.maven</groupId> + <artifactId>maven-embedder</artifactId> + <version>2.0.4</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + </dependencies> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/MavenArtifactRepository.java b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/MavenArtifactRepository.java new file mode 100644 index 0000000000..b2c608da63 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/MavenArtifactRepository.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.services.maven; + +import java.util.Collection; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.services.artifact.Artifact; +import org.apache.tuscany.spi.services.artifact.ArtifactRepository; +import org.apache.tuscany.host.RuntimeInfo; +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Property; + +/** + * Artifact repository used for resolving artifacts. + * + * This is used by the composite loader for resolving artifacts transitively. The repository uses the Maven API for resolving dependencies and hence + * expects the artifacts to be stored in a structure similar to the Maven repository layout. The repository first looks within the deployed unit (WAR + * for example), before resorting to a local and set of remote Maven repositories. + * + * @version $Rev$ $Date$ + */ +public class MavenArtifactRepository implements ArtifactRepository { + + /** Maven helper */ + private MavenHelper mavenHelper; + + /** WAR repository helper */ + private WarRepositoryHelper warRepositoryHelper; + + /** + * Conctructs a new artifact repository. + */ + public MavenArtifactRepository(@Property(name = "remoteRepoUrl") + String remoteRepoUrl, @Autowire + RuntimeInfo runtimeInfo) { + mavenHelper = new MavenHelper(remoteRepoUrl, runtimeInfo.isOnline()); + warRepositoryHelper = new WarRepositoryHelper(runtimeInfo.getBaseURL()); + mavenHelper.start(); + } + + /** + * Resolve an artifact. This ensures that the information associated with an artifact is fully populated; Specifically, after this operation the + * URL should contain a location where the artifact can be obtained. + * + * @param artifact + * the artifact to be resolved + */ + public void resolve(Artifact rootArtifact) { + if(warRepositoryHelper.resolveTransitively(rootArtifact)) { + return; + } + if(mavenHelper.resolveTransitively(rootArtifact)) { + return; + } + TuscanyDependencyException tde = new TuscanyDependencyException("Unable to resolve artifact: " + rootArtifact); + tde.setIdentifier(rootArtifact.toString()); + throw tde; + } + + /** + * Resolve a collection of Artifacts. + * + * @param artifacts + * a collection of artifacts to be resolved + * @see #resolve(Artifact) + */ + public void resolve(Collection<? extends Artifact> artifacts) { + for (Artifact artifact : artifacts) { + resolve(artifact); + } + } + + /** + * Destroy method. + * + */ + @Destroy + public void destroy() { + mavenHelper.stop(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/MavenHelper.java b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/MavenHelper.java new file mode 100644 index 0000000000..f68ad562f7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/MavenHelper.java @@ -0,0 +1,291 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.services.maven; + +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; +import org.apache.maven.artifact.metadata.ArtifactMetadataSource; +import org.apache.maven.artifact.metadata.ResolutionGroup; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; +import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; +import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; +import org.apache.maven.artifact.resolver.ArtifactNotFoundException; +import org.apache.maven.artifact.resolver.ArtifactResolutionException; +import org.apache.maven.artifact.resolver.ArtifactResolutionResult; +import org.apache.maven.artifact.resolver.ArtifactResolver; +import org.apache.tuscany.spi.services.artifact.Artifact; +import org.codehaus.classworlds.ClassWorld; +import org.codehaus.classworlds.DefaultClassRealm; +import org.codehaus.classworlds.DuplicateRealmException; +import org.codehaus.plexus.PlexusContainerException; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import org.codehaus.plexus.embed.Embedder; + +/** + * Utility class for embedding Maven. + * + * @version $Rev$ $Date$ + */ +public class MavenHelper { + + /** Local repository */ + private static final File LOCAL_REPO = new File(System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository"); + + /** Remote repository URLs */ + private final String[] remoteRepositoryUrls; + + /** Maven metadata source */ + private ArtifactMetadataSource metadataSource; + + /** Artifact factory */ + private ArtifactFactory artifactFactory; + + /** Local artifact repository */ + private ArtifactRepository localRepository; + + /** Remote artifact repositories */ + private List<ArtifactRepository> remoteRepositories = new LinkedList<ArtifactRepository>(); + + /** Artifact resolver */ + private ArtifactResolver artifactResolver; + + /** Online */ + private boolean online; + + /** + * Initialize the remote repository URLs. + * + * @param remoteRepositoryUrls + * Remote repository URLS. + * @param runtimeInfo + * Runtime information. + */ + public MavenHelper(String remoteRepositoryUrl, boolean online) { + this.remoteRepositoryUrls = remoteRepositoryUrl.split(","); + this.online = online; + } + + /** + * Starts the embedder. + * + * @throws TuscanyDependencyException + * If unable to start the embedder. + */ + public void start() throws TuscanyDependencyException { + + try { + + Embedder embedder = new Embedder(); + ClassWorld classWorld = new ClassWorld(); + + classWorld.newRealm("plexus.core", getClass().getClassLoader()); + + // Evil hack for Tomcat classloader issue - starts + Field realmsField = ClassWorld.class.getDeclaredField("realms"); + realmsField.setAccessible(true); + Map realms = (Map) realmsField.get(classWorld); + DefaultClassRealm realm = (DefaultClassRealm) realms.get("plexus.core"); + + Class clazz = Class.forName("org.codehaus.classworlds.RealmClassLoader"); + Constructor ctr = clazz.getDeclaredConstructor(new Class[] { DefaultClassRealm.class, ClassLoader.class }); + ctr.setAccessible(true); + Object realmClassLoader = ctr.newInstance(realm, getClass().getClassLoader()); + + Field realmClassLoaderField = DefaultClassRealm.class.getDeclaredField("classLoader"); + realmClassLoaderField.setAccessible(true); + realmClassLoaderField.set(realm, realmClassLoader); + // Evil hack for Tomcat classloader issue - ends + + embedder.start(classWorld); + + metadataSource = (ArtifactMetadataSource) embedder.lookup(ArtifactMetadataSource.ROLE); + artifactFactory = (ArtifactFactory) embedder.lookup(ArtifactFactory.ROLE); + artifactResolver = (ArtifactResolver) embedder.lookup(ArtifactResolver.ROLE); + + setUpRepositories(embedder); + + embedder.stop(); + + } catch (DuplicateRealmException ex) { + throw new TuscanyDependencyException(ex); + } catch (PlexusContainerException ex) { + throw new TuscanyDependencyException(ex); + } catch (ComponentLookupException ex) { + throw new TuscanyDependencyException(ex); + } catch (NoSuchFieldException ex) { + throw new TuscanyDependencyException(ex); + } catch (IllegalAccessException ex) { + throw new TuscanyDependencyException(ex); + } catch (ClassNotFoundException ex) { + throw new TuscanyDependencyException(ex); + } catch (NoSuchMethodException ex) { + throw new TuscanyDependencyException(ex); + } catch (InstantiationException ex) { + throw new TuscanyDependencyException(ex); + } catch (InvocationTargetException ex) { + throw new TuscanyDependencyException(ex); + } + + } + + /** + * Stops the embedder. + * + * @throws TuscanyDependencyException + * If unable to stop the embedder. + */ + public void stop() throws TuscanyDependencyException { + } + + /** + * Resolves the dependencies transitively. + * + * @param artifact + * Artifact whose dependencies need to be resolved. + * @throws TuscanyDependencyException + * If unable to resolve the dependencies. + */ + public boolean resolveTransitively(Artifact rootArtifact) throws TuscanyDependencyException { + + org.apache.maven.artifact.Artifact mavenRootArtifact = artifactFactory.createArtifact(rootArtifact.getGroup(), rootArtifact.getName(), + rootArtifact.getVersion(), org.apache.maven.artifact.Artifact.SCOPE_RUNTIME, rootArtifact.getType()); + + try { + + if (resolve(mavenRootArtifact)) { + rootArtifact.setUrl(mavenRootArtifact.getFile().toURL()); + if (resolveDependencies(rootArtifact, mavenRootArtifact)) { + return true; + } else { + return false; + } + } else { + return false; + } + } catch (MalformedURLException ex) { + throw new TuscanyDependencyException(ex); + } + + } + + /* + * Resolves the artifact. + */ + private boolean resolve(org.apache.maven.artifact.Artifact mavenRootArtifact) { + + try { + artifactResolver.resolve(mavenRootArtifact, remoteRepositories, localRepository); + return true; + } catch (ArtifactResolutionException ex) { + return false; + } catch (ArtifactNotFoundException ex) { + return false; + } + + } + + /* + * Sets up local and remote repositories. + */ + private void setUpRepositories(Embedder embedder) { + + try { + + ArtifactRepositoryFactory artifactRepositoryFactory = (ArtifactRepositoryFactory) embedder.lookup(ArtifactRepositoryFactory.ROLE); + + ArtifactRepositoryLayout layout = (ArtifactRepositoryLayout) embedder.lookup(ArtifactRepositoryLayout.ROLE, "default"); + + String updatePolicy = online ? ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS : ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER; + ArtifactRepositoryPolicy snapshotsPolicy = new ArtifactRepositoryPolicy(true, updatePolicy, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); + ArtifactRepositoryPolicy releasesPolicy = new ArtifactRepositoryPolicy(true, updatePolicy, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); + + localRepository = artifactRepositoryFactory.createArtifactRepository("local", LOCAL_REPO.toURL().toExternalForm(), layout, + snapshotsPolicy, releasesPolicy); + + if (!online) { + return; + } + + for (String remoteRepositoryUrl : remoteRepositoryUrls) { + String repoid = remoteRepositoryUrl.replace(':', '_'); + repoid = repoid.replace('/', '_'); + repoid = repoid.replace('\\', '_'); + remoteRepositories.add(artifactRepositoryFactory.createArtifactRepository(repoid, remoteRepositoryUrl, layout, snapshotsPolicy, + releasesPolicy)); + } + + } catch (MalformedURLException ex) { + throw new TuscanyDependencyException(ex); + } catch (ComponentLookupException ex) { + throw new TuscanyDependencyException(ex); + } + + } + + /* + * Resolves transitive dependencies. + */ + private boolean resolveDependencies(Artifact rootArtifact, org.apache.maven.artifact.Artifact mavenRootArtifact) { + + try { + + ResolutionGroup resolutionGroup = null; + ArtifactResolutionResult result = null; + + resolutionGroup = metadataSource.retrieve(mavenRootArtifact, localRepository, remoteRepositories); + result = artifactResolver.resolveTransitively(resolutionGroup.getArtifacts(), mavenRootArtifact, remoteRepositories, localRepository, + metadataSource); + + // Add the artifacts to the deployment unit + for (Object obj : result.getArtifacts()) { + org.apache.maven.artifact.Artifact depArtifact = (org.apache.maven.artifact.Artifact) obj; + Artifact artifact = new Artifact(); + artifact.setName(mavenRootArtifact.getArtifactId()); + artifact.setGroup(mavenRootArtifact.getGroupId()); + artifact.setType(mavenRootArtifact.getType()); + artifact.setClassifier(mavenRootArtifact.getClassifier()); + artifact.setUrl(depArtifact.getFile().toURL()); + rootArtifact.addDependency(artifact); + } + + } catch (ArtifactMetadataRetrievalException ex) { + return false; + } catch (MalformedURLException ex) { + throw new TuscanyDependencyException(ex); + } catch (ArtifactResolutionException ex) { + return false; + } catch (ArtifactNotFoundException ex) { + return false; + } + + return true; + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/TuscanyDependencyException.java b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/TuscanyDependencyException.java new file mode 100644 index 0000000000..6e89443711 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/TuscanyDependencyException.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.services.maven; + +import org.apache.tuscany.api.TuscanyRuntimeException; + +/** + * Exception thrown in case of an artifact error. + * + * @version $Rev$ $Date$ + */ +public class TuscanyDependencyException extends TuscanyRuntimeException { + + /** + * Initializes the cause. + * @param cause Cause of the exception. + */ + public TuscanyDependencyException(Throwable cause) { + super(cause); + } + + /** + * Initializes the message. + * @param message Message of the exception. + */ + public TuscanyDependencyException(String message) { + super(message); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/WarRepositoryHelper.java b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/WarRepositoryHelper.java new file mode 100644 index 0000000000..be4ee68bfa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/main/java/org/apache/tuscany/services/maven/WarRepositoryHelper.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.services.maven; + +import java.beans.XMLDecoder; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.tuscany.spi.services.artifact.Artifact; +import org.codehaus.plexus.util.IOUtil; + +/** + * Helper class for resolving dependencies from WAR files. + * + * @author Administrator + * + */ +public class WarRepositoryHelper { + + /** WAR Repository URL */ + private URL reporsitoryUrl; + + /** Dependency metadata */ + private Map<String, Set<String>> transDependencyMap = new HashMap<String, Set<String>>(); + + /** + * Initializes the repository URL. + * @param baseUrl Base URL. + */ + @SuppressWarnings("unchecked") + public WarRepositoryHelper(URL baseUrl) { + + + InputStream transDepMapInputStream = null; + try { + + reporsitoryUrl = new URL(baseUrl, "repository/"); + URL transDependencyMapUrl = new URL(baseUrl, "repository/dependency.metadata"); + transDepMapInputStream = transDependencyMapUrl.openStream(); + + XMLDecoder decoder = new XMLDecoder(transDepMapInputStream); + transDependencyMap = (Map<String, Set<String>>)decoder.readObject(); + decoder.close(); + + } catch (MalformedURLException ex) { + // throw new TuscanyDependencyException(ex); + } catch (IOException ex) { + // throw new TuscanyDependencyException(ex); + } finally { + IOUtil.close(transDepMapInputStream); + } + + } + + /** + * Resolves the dependencies transitively. + * + * @param artifact + * Artifact whose dependencies need to be resolved. + * @throws TuscanyDependencyException + * If unable to resolve the dependencies. + */ + public boolean resolveTransitively(Artifact rootArtifact) throws TuscanyDependencyException { + + String artKey = rootArtifact.getGroup() + "/" + rootArtifact.getName() + "/" + rootArtifact.getVersion() + "/"; + if(!transDependencyMap.containsKey(artKey)) { + return false; + } + + + for(String dep : transDependencyMap.get(artKey)) { + + String[] tokens = dep.split("/"); + String artName = tokens[1]; + + try { + if(artName.equals(rootArtifact.getName())) { + rootArtifact.setUrl(new URL(reporsitoryUrl, dep)); + } else { + Artifact depArtifact = new Artifact(); + depArtifact.setGroup(tokens[0]); + depArtifact.setName(tokens[1]); + depArtifact.setVersion(tokens[2]); + depArtifact.setUrl(new URL(reporsitoryUrl, dep)); + rootArtifact.addDependency(depArtifact); + + } + } catch (MalformedURLException ex) { + throw new TuscanyDependencyException(ex); + } + } + return true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/java/org/apache/tuscany/services/maven/MavenArtifactRepositoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/java/org/apache/tuscany/services/maven/MavenArtifactRepositoryTestCase.java new file mode 100644 index 0000000000..2eeb4e2e66 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/java/org/apache/tuscany/services/maven/MavenArtifactRepositoryTestCase.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.services.maven; + +import java.io.File; +import java.net.URL; +import java.util.Set; + +import junit.framework.TestCase; + +import org.apache.tuscany.host.RuntimeInfo; +import org.apache.tuscany.spi.services.artifact.Artifact; + +/** + * @version $Rev$ $Date$ + */ +public class MavenArtifactRepositoryTestCase extends TestCase { + + public MavenArtifactRepositoryTestCase(String arg0) { + super(arg0); + } + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + /* + * Test method for 'org.apache.tuscany.services.maven.MavenArtifactRepository.resolve(Artifact)' + */ + public void testResolveArtifact() throws Exception { + + final URL BASE_URL = new File(System.getProperty("user.home") + File.separator + ".m2").toURL(); + String remoteRepoUrl = "http://repo1.maven.org/maven2/"; + MavenArtifactRepository repository = new MavenArtifactRepository(remoteRepoUrl, new RuntimeInfo() { + public File getApplicationRootDirectory() { + return null; + } + + public URL getBaseURL() { + return BASE_URL; + } + + public File getInstallDirectory() { + return null; + } + + public boolean isOnline() { + return false; + } + }); + Artifact artifact = new Artifact(); + artifact.setGroup("junit"); + artifact.setName("junit"); + artifact.setVersion("3.8.1"); + artifact.setType("jar"); + + repository.resolve(artifact); + + Set<URL> urls = artifact.getUrls(); + + System.err.println(urls); + + assertEquals(1, urls.size()); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/java/org/apache/tuscany/services/maven/WarRepositoryHelperTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/java/org/apache/tuscany/services/maven/WarRepositoryHelperTestCase.java new file mode 100644 index 0000000000..3a79599fa7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/java/org/apache/tuscany/services/maven/WarRepositoryHelperTestCase.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.services.maven; + +import java.net.URL; +import java.net.URLClassLoader; + +import org.apache.tuscany.spi.services.artifact.Artifact; + +import junit.framework.TestCase; + +/** + * @author Administrator + * + */ +public class WarRepositoryHelperTestCase extends TestCase { + + /** + * @param arg0 + */ + public WarRepositoryHelperTestCase(String arg0) { + super(arg0); + } + + /** + * Test method for {@link org.apache.tuscany.services.maven.WarRepositoryHelper#WarRepositoryHelper(java.net.URL)}. + */ + public void testWarRepositoryHelper() { + + URL warUrl = getClass().getClassLoader().getResource("webapp.war"); + URLClassLoader urlc = new URLClassLoader(new URL[] {warUrl}); + + URL repoUrl = urlc.getResource("WEB-INF/tuscany/"); + System.err.println(repoUrl); + + WarRepositoryHelper warRepositoryHelper = new WarRepositoryHelper(repoUrl); + assertNotNull(warRepositoryHelper); + + } + + /** + * Test method for {@link org.apache.tuscany.services.maven.WarRepositoryHelper#WarRepositoryHelper(java.net.URL)}. + */ + public void testResolveTransitively() { + + URL warUrl = getClass().getClassLoader().getResource("webapp.war"); + URLClassLoader urlc = new URLClassLoader(new URL[] {warUrl}); + + URL repoUrl = urlc.getResource("WEB-INF/tuscany/"); + WarRepositoryHelper warRepositoryHelper = new WarRepositoryHelper(repoUrl); + + Artifact artifact = new Artifact(); + artifact.setGroup("commons-httpclient"); + artifact.setName("commons-httpclient"); + artifact.setVersion("3.0"); + + warRepositoryHelper.resolveTransitively(artifact); + assertEquals(4, artifact.getUrls().size()); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/resources/webapp.war b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/resources/webapp.war Binary files differnew file mode 100644 index 0000000000..4448aca8ff --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/maven/src/test/resources/webapp.war diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/pom.xml new file mode 100644 index 0000000000..df90006ade --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/pom.xml @@ -0,0 +1,70 @@ +<?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> + + <parent> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>persistence-common</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany JPA</name> + <description>Tuscany JPA Integration.</description> + + + <repositories> + <repository> + <id>java.net</id> + <url>https://maven-repository.dev.java.net/nonav/repository</url> + <layout>legacy</layout> + </repository> + </repositories> + + + <dependencies> + <dependency> + <groupId>javax.persistence</groupId> + <artifactId>persistence-api</artifactId> + <version>1.0</version> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-api</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitProcessor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitProcessor.java new file mode 100644 index 0000000000..77ac0ef018 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitProcessor.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import javax.persistence.PersistenceUnit; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.implementation.java.AbstractPropertyProcessor; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; + +/** + * Annotation processor for injecting <code>PersistenceUnit</code> + * annotations on properties. + * + */ +public class PersistenceUnitProcessor extends AbstractPropertyProcessor<PersistenceUnit> { + + /** + * Injects the implementation processor service. + * @param service Implementation processor service. + */ + public PersistenceUnitProcessor(@Autowire ImplementationProcessorService service) { + super(PersistenceUnit.class, service); + } + + /** + * Defaults to the field name. + */ + @Override + protected String getName(PersistenceUnit persistenceUnit) { + return null; + } + + /** + * Initializes the property. + */ + @SuppressWarnings("unchecked") + protected <EntityManagerFactory> void initProperty(JavaMappedProperty<EntityManagerFactory> property, + PersistenceUnit annotation, + CompositeComponent parent, + DeploymentContext context) { + String unitName = annotation.unitName(); + final EntityManagerFactory emf = (EntityManagerFactory)parent.getSystemChild(unitName); + if(emf == null) { + // TODO Create an EMF, also clarify from jmarino what the second argument is. + parent.registerJavaObject(unitName, null, emf); + } + property.setDefaultValueFactory(new ObjectFactory<EntityManagerFactory>() { + public EntityManagerFactory getInstance() throws ObjectCreationException { + return emf; + } + }); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/.ruleset new file mode 100644 index 0000000000..3886f07f2d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/.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-M2/sca/services/persistence/openjpa/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/pom.xml new file mode 100644 index 0000000000..38aaecdd5a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/pom.xml @@ -0,0 +1,62 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services.idl</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>openjpa</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany OpenJPA</name> + <description>TuscanyOpenJPA Integration.</description> + + + <repositories> + <repository> + <id>apache-snapshots</id> + <url>http://people.apache.org/repo/m2-snapshot-repository</url> + </repository> + </repositories> + + + <dependencies> + <dependency> + <groupId>org.apache.openjpa</groupId> + <artifactId>openjpa-persistence-jdbc</artifactId> + <version>0.9.0-incubating-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/Constants.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/Constants.java new file mode 100644 index 0000000000..820f57bcad --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/Constants.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.service.openjpa; + +/** + * Constants used by the JPA extension + * + * @version $Rev$ $Date$ + */ +public final class Constants { + + public static final String PERSISTENCE_UNIT = "persistenceUnit"; + public static final String CONFIG_PROPERTIES = "configProperties"; + + private Constants() { + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryImplementation.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryImplementation.java new file mode 100644 index 0000000000..d818f145bd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryImplementation.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import org.apache.tuscany.spi.model.AtomicImplementation; +import org.apache.tuscany.spi.model.ComponentType; + +/** + * Represents the implementation type of a system service that manages JPA + * <code>EntityManagerFactoryImplementation</code> implementations + * + * @version $Rev$ $Date$ + */ +public class EntityManagerFactoryImplementation extends AtomicImplementation<ComponentType> { + + public EntityManagerFactoryImplementation() { + } + + public EntityManagerFactoryImplementation(ComponentType componentType) { + super(componentType); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerObjectFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerObjectFactory.java new file mode 100644 index 0000000000..45d4e1a077 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerObjectFactory.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.service.openjpa; + +import java.util.Map; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.ObjectFactory; + +/** + * Creates a JPA <code>EntityManager</code> to be injected on a component implementation instance. + * + * @version $Rev$ $Date$ + */ +public class EntityManagerObjectFactory implements ObjectFactory<EntityManager> { + + private EntityManagerFactory emf; + private Map props; + + public EntityManagerObjectFactory(EntityManagerFactory emf) { + this.emf = emf; + } + + public EntityManagerObjectFactory(EntityManagerFactory emf, Map props) { + this.emf = emf; + this.props = props; + } + + public EntityManager getInstance() throws ObjectCreationException { + if (props == null) { + return emf.createEntityManager(); + } else { + return emf.createEntityManager(props); + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerProcessor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerProcessor.java new file mode 100644 index 0000000000..9574f60b8c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerProcessor.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import java.lang.reflect.Member; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceContext; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.implementation.java.AbstractPropertyProcessor; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.ProcessingException; + + +/** + * Evaluates constructors, methods, and fields annotated with {@link PersistenceContext }, creating a mapped property + * that will inject an {@link EntityManager} on an implementation instance. + * + * @version $Rev$ $Date$ + */ +public class EntityManagerProcessor extends AbstractPropertyProcessor<PersistenceContext> { + + public EntityManagerProcessor(@Autowire ImplementationProcessorService service) { + super(PersistenceContext.class, service); + } + + protected String getName(PersistenceContext annotation) { + String name = annotation.unitName(); + if (name == null) { + return "_defaultJPAPersistenceUnit"; + } + return name; + } + + protected <T>JavaMappedProperty<T> createProperty(String name, + Class<T> javaType, + Member member) throws ProcessingException { + if (!EntityManager.class.equals(javaType)) { + InvalidInjectionSite e = + new InvalidInjectionSite("Injection site must by of type " + EntityManager.class.getName()); + e.setIdentifier(name); + throw e; + } + return super.createProperty(name, javaType, member); + } + + @SuppressWarnings("unchecked") + protected <T> void initProperty(JavaMappedProperty<T> property, + PersistenceContext annotation, + CompositeComponent parent, + DeploymentContext context) { + EntityManagerFactory emf = parent.resolveSystemInstance(EntityManagerFactory.class); + ObjectFactory factory = new EntityManagerObjectFactory(emf); + property.setDefaultValueFactory(factory); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/InvalidInjectionSite.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/InvalidInjectionSite.java new file mode 100644 index 0000000000..11c5e9dfc7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/InvalidInjectionSite.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import org.apache.tuscany.spi.implementation.java.ProcessingException; + +/** + * @version $Rev$ $Date$ + */ +public class InvalidInjectionSite extends ProcessingException { + public InvalidInjectionSite() { + } + + public InvalidInjectionSite(String message) { + super(message); + } + + public InvalidInjectionSite(String message, Throwable cause) { + super(message, cause); + } + + public InvalidInjectionSite(Throwable cause) { + super(cause); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAAtomicComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAAtomicComponent.java new file mode 100644 index 0000000000..1e440bf0d3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAAtomicComponent.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import java.util.ArrayList; +import java.util.Map; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.TargetException; +import org.apache.tuscany.spi.extension.SystemAtomicComponentExtension; + +/** + * A system service that manages a JPA <code>EntityManagerFactory</code>. This service is used by {@link + * EntityManagerProcessor} to inject an <code>EntityManager<code> on a constructor parameter, field, or method of an + * implementation instance. Since a JPA persistence context is specific to an application, this system service is scoped + * to the application composite. That is, it is contained as a system child of the application composite. + * + * @version $Rev$ $Date$ + */ +public class JPAAtomicComponent extends SystemAtomicComponentExtension { + private EntityManagerFactory factory; + private String persistenceUnit; + private Map<Object, Object> configProps; + + public JPAAtomicComponent(String name, + CompositeComponent parent, + ScopeContainer scopeContainer, + String persistenceUnit, + Map<Object, Object> configProps, + int initLevel) { + super(name, null, parent, scopeContainer, initLevel); + assert persistenceUnit != null; + this.persistenceUnit = persistenceUnit; + this.configProps = configProps; + interfazes = new ArrayList<Class<?>>(); + interfazes.add(EntityManagerFactory.class); + } + + public Object createInstance() throws ObjectCreationException { + if (configProps != null) { + factory = Persistence.createEntityManagerFactory(persistenceUnit, configProps); + } else { + factory = Persistence.createEntityManagerFactory(persistenceUnit); + } + return factory; + } + + public Object getTargetInstance() throws TargetException { + return factory; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAComponentBuilder.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAComponentBuilder.java new file mode 100644 index 0000000000..65b3313515 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAComponentBuilder.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.service.openjpa; + +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentBuilderExtension; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Property; + +import static org.apache.tuscany.service.openjpa.Constants.PERSISTENCE_UNIT; + +/** + * @version $Rev$ $Date$ + */ +public class JPAComponentBuilder extends ComponentBuilderExtension { + protected Class getImplementationType() { + return null; + } + + public Component build(CompositeComponent parent, ComponentDefinition definition, DeploymentContext ctx) + throws BuilderConfigException { +// String name = definition.getName(); +// ScopeContainer moduleScope = ctx.getModuleScope(); +// Integer initLevel = definition.getInitLevel(); + ComponentType<?, ?, ?> type = definition.getImplementation().getComponentType(); + Property<?> persistenceUnit = type.getProperties().get(PERSISTENCE_UNIT); + if (persistenceUnit == null) { + BuilderConfigException e = + new BuilderConfigException("Persistence Unit not specified in JPA import in composite"); + e.setIdentifier(parent.getName()); + throw e; + } +// Property<?> configProps = type.getProperties().get(PERSISTENCE_UNIT); + return null; +// return new JPAAtomicComponent(name, parent, moduleScope, initLevel); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAImportLoader.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAImportLoader.java new file mode 100644 index 0000000000..07969d095c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAImportLoader.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.service.openjpa; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.model.ModelObject; + +/** + * @version $Rev$ $Date$ + */ +public class JPAImportLoader extends LoaderExtension { + private static final QName IMPORT = new QName(XML_NAMESPACE_1_0, "import.jpa"); + + public JPAImportLoader(@Autowire LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return IMPORT; + } + + public ModelObject load(CompositeComponent parent, XMLStreamReader reader, DeploymentContext deploymentContext) + throws XMLStreamException, LoaderException { + //ComponentDefinition definition = new ComponentDefinition() + // TODO read in persisitence unit setting and properties, and set them as properties on the component + return null; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/test/java/org/apache/tuscany/service/openjpa/EntityManagerProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/test/java/org/apache/tuscany/service/openjpa/EntityManagerProcessorTestCase.java new file mode 100644 index 0000000000..ec33c81d1e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/openjpa/src/test/java/org/apache/tuscany/service/openjpa/EntityManagerProcessorTestCase.java @@ -0,0 +1,128 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceContext; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessor; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +import junit.framework.TestCase; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class EntityManagerProcessorTestCase extends TestCase { + + private ImplementationProcessor processor; + private CompositeComponent parent; + + public void testVisitMethod() throws Exception { + Method method = Foo.class.getMethod("setBar", EntityManager.class); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitMethod(parent, method, type, null); + JavaMappedProperty<?> prop = type.getProperties().get("bar"); + assertEquals(EntityManagerObjectFactory.class, prop.getDefaultValueFactory().getClass()); + } + + public void testVisitBadMethod() throws Exception { + Method method = Foo.class.getMethod("setBadBar", String.class); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + try { + processor.visitMethod(parent, method, type, null); + fail(); + } catch (InvalidInjectionSite e) { + // expected + } + } + + public void testVisitField() throws Exception { + Field field = Foo.class.getDeclaredField("bar"); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitField(parent, field, type, null); + JavaMappedProperty<?> prop = type.getProperties().get("bar"); + assertEquals(EntityManagerObjectFactory.class, prop.getDefaultValueFactory().getClass()); + } + + public void testBadVisitField() throws Exception { + Field field = Foo.class.getDeclaredField("badField"); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + try { + processor.visitField(null, field, type, null); + fail(); + } catch (InvalidInjectionSite e) { + // expected + } + } + + @SuppressWarnings("unchecked") + protected void setUp() throws Exception { + super.setUp(); + EntityManagerFactory emf = EasyMock.createMock(EntityManagerFactory.class); + EasyMock.replay(emf); + parent = EasyMock.createMock(CompositeComponent.class); + EasyMock.expect(parent.resolveSystemInstance(EntityManagerFactory.class)).andReturn(emf).atLeastOnce(); + EasyMock.replay(parent); + ImplementationProcessorService service = EasyMock.createMock(ImplementationProcessorService.class); + service.addName(EasyMock.isA(List.class), EasyMock.eq(0), EasyMock.isA(String.class)); + EasyMock.expectLastCall().andStubAnswer(new IAnswer() { + public Object answer() throws Throwable { + ((List<Object>) EasyMock.getCurrentArguments()[0]).add(EasyMock.getCurrentArguments()[2]); + return null; + } + }); + EasyMock.replay(service); + processor = new EntityManagerProcessor(service); + } + + private static class Foo { + + + @PersistenceContext + protected EntityManager bar; + + @PersistenceContext + protected String badField; + + @PersistenceContext + public void setBar(EntityManager d) { + } + + @PersistenceContext + public void setBadBar(String d) { + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/pom.xml new file mode 100644 index 0000000000..6b3a7ed9d1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/persistence/pom.xml @@ -0,0 +1,61 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca.services</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.tuscany.sca.services.persistence</groupId> + <artifactId>parent</artifactId> + <packaging>pom</packaging> + <name>Tuscany SCA Persistence Services</name> + + <!-- definition of repositories where the parent pom can be found --> + <repositories> + <repository> + <id>apache.snapshots</id> + <name>Apache Snapshot Repository</name> + <url>http://people.apache.org/repo/m2-snapshot-repository</url> + <releases> + <enabled>false</enabled> + </releases> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>apache.incubator</id> + <name>Apache Incubator Repository</name> + <url>http://people.apache.org/repo/m2-incubating-repository/</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + + <modules> + <module>openjpa</module> + </modules> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/pom.xml new file mode 100644 index 0000000000..81ccaf16fd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/pom.xml @@ -0,0 +1,68 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.tuscany.sca.services</groupId> + <artifactId>parent</artifactId> + <packaging>pom</packaging> + <name>Tuscany SCA Services</name> + + <!-- definition of repositories where the parent pom can be found --> + <repositories> + <repository> + <id>apache.snapshots</id> + <name>Apache Snapshot Repository</name> + <url>http://people.apache.org/repo/m2-snapshot-repository</url> + <releases> + <enabled>false</enabled> + </releases> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>apache.incubator</id> + <name>Apache Incubator Repository</name> + <url>http://people.apache.org/repo/m2-incubating-repository/</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + + <modules> + <module>idl</module> + <module>containers</module> + <module>databinding</module> + <module>bindings</module> + <module>maven</module> +<!-- + <module>transports/http.jetty</module> +--> + </modules> +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/.ruleset b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/.ruleset new file mode 100644 index 0000000000..3886f07f2d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/.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-M2/sca/services/transports/http.jetty/LICENSE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/NOTICE.txt b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +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. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/pom.xml b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/pom.xml new file mode 100644 index 0000000000..3fd0189fba --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/pom.xml @@ -0,0 +1,68 @@ +<?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> + <parent> + <groupId>org.apache.tuscany.services</groupId> + <artifactId>services</artifactId> + <version>1.0-incubator-M2-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>http-jetty</artifactId> + <name>Apache Tuscany Jetty HTTP Service</name> + <description>Tuscany Jetty HTTP Service</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>jetty</groupId> + <artifactId>jetty</artifactId> + <version>6.0.0beta17</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>jetty</groupId> + <artifactId>jetty-util</artifactId> + <version>6.0.0beta16</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + </dependency> + <dependency> + <groupId>org.apache.geronimo.specs</groupId> + <artifactId>geronimo-j2ee-connector_1.5_spec</artifactId> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + </dependencies> + +</project> diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyLogger.java b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyLogger.java new file mode 100644 index 0000000000..d42b301fbb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyLogger.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.service.jetty; + +import org.mortbay.log.Logger; + +/** + * Serves as a wrapper for a {@link TransportMonitor} to replace Jetty's logging mechanism + * + * @version $Rev$ $Date$ + */ +public class JettyLogger implements Logger { + + private TransportMonitor monitor; + private boolean debugEnabled; + + public void setMonitor(TransportMonitor monitor) { + this.monitor = monitor; + } + + public boolean isDebugEnabled() { + return debugEnabled; + } + + public void setDebugEnabled(boolean debugEnabled) { + this.debugEnabled = debugEnabled; + } + + public void info(String msg, Object arg0, Object arg1) { + if (monitor != null) { + monitor.debug(msg, arg0, arg1); + } else if (debugEnabled) { + System.err.println(":INFO: " + format(msg, arg0, arg1)); + } + } + + public void debug(String msg, Throwable th) { + if (debugEnabled) { + if (monitor != null) { + monitor.debug(msg, th); + } else { + System.err.println(":DEBUG: " + msg); + th.printStackTrace(); + } + } + } + + public void debug(String msg, Object arg0, Object arg1) { + if (debugEnabled) { + if (monitor != null) { + monitor.debug(msg, arg0, arg1); + } else { + System.err.println(":DEBUG: " + format(msg, arg0, arg1)); + } + } + } + + public void warn(String msg, Object arg0, Object arg1) { + if (monitor != null) { + monitor.warn(msg, arg0, arg1); + } else if (debugEnabled) { + System.err.println(":WARN: " + format(msg, arg0, arg1)); + } + } + + public void warn(String msg, Throwable th) { + if (monitor != null) { + monitor.warn(msg, th); + } else if (debugEnabled) { + System.err.println(":WARN: " + msg); + th.printStackTrace(); + } + } + + public Logger getLogger(String name) { + return this; + } + + private String format(String msg, Object arg0, Object arg1) { + int i0 = msg.indexOf("{}"); + int i1 = i0 < 0 ? -1 : msg.indexOf("{}", i0 + 2); + if (arg1 != null && i1 >= 0) { + msg = msg.substring(0, i1) + arg1 + msg.substring(i1 + 2); + } + if (arg0 != null && i0 >= 0) { + msg = msg.substring(0, i0) + arg0 + msg.substring(i0 + 2); + } + return msg; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyService.java b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyService.java new file mode 100644 index 0000000000..6fd68813df --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyService.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.jetty; + +import org.apache.tuscany.spi.host.ServletHost; + +import org.mortbay.jetty.Server; + +/** + * Implementations provide a Jetty transport service to the runtime + * + * @version $$Rev$$ $$Date$$ + */ +public interface JettyService extends ServletHost { + + /** + * Returns the active Jetty server + */ + Server getServer(); + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyServiceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyServiceImpl.java new file mode 100644 index 0000000000..01ad06fbe9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/JettyServiceImpl.java @@ -0,0 +1,314 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.service.jetty; + +import java.io.File; +import java.io.IOException; +import javax.resource.spi.work.Work; +import javax.servlet.Servlet; + +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Scope; +import org.osoa.sca.annotations.Service; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.api.annotation.Monitor; +import org.apache.tuscany.spi.host.ServletHost; +import org.apache.tuscany.spi.services.work.WorkScheduler; + +import org.mortbay.jetty.Connector; +import org.mortbay.jetty.Server; +import org.mortbay.jetty.handler.ContextHandler; +import org.mortbay.jetty.nio.SelectChannelConnector; +import org.mortbay.jetty.security.SslSocketConnector; +import org.mortbay.jetty.servlet.ServletHandler; +import org.mortbay.jetty.servlet.ServletHolder; +import org.mortbay.jetty.servlet.ServletMapping; +import org.mortbay.log.Log; +import org.mortbay.log.Logger; +import org.mortbay.thread.BoundedThreadPool; +import org.mortbay.thread.ThreadPool; + +/** + * Implements an HTTP transport service using Jetty. + * + * @version $$Rev$$ $$Date$$ + */ +@Scope("MODULE") +@Service(ServletHost.class) +public class JettyServiceImpl implements JettyService { + + private static final String ROOT = "/"; + private static final int ERROR = 0; + private static final int UNINITIALIZED = 0; + private static final int STARTING = 1; + private static final int STARTED = 2; + private static final int STOPPING = 3; + private static final int STOPPED = 4; + + private final Object joinLock = new Object(); + private int state = UNINITIALIZED; + private int httpPort = 8080; + private int httpsPort = 8484; + private String keystore; + private String certPassword; + private String keyPassword; + private boolean sendServerVersion; + private boolean https; + private TransportMonitor monitor; + private WorkScheduler scheduler; + private boolean debug; + private Server server; + private Connector connector; + private ServletHandler servletHandler; + + static { + // hack to replace the static Jetty logger + System.setProperty("org.mortbay.log.class", JettyLogger.class.getName()); + } + + public JettyServiceImpl(@Monitor TransportMonitor monitor, + @Autowire WorkScheduler scheduler) { + this.monitor = monitor; + this.scheduler = scheduler; + // Jetty uses a static logger, so jam in the monitor into a static reference + Logger logger = Log.getLogger(null); + if (logger instanceof JettyLogger) { + JettyLogger jettyLogger = (JettyLogger) logger; + jettyLogger.setMonitor(monitor); + if (debug) { + jettyLogger.setDebugEnabled(true); + } + } + } + + public JettyServiceImpl(TransportMonitor monitor) { + this.monitor = monitor; + } + + public JettyServiceImpl(TransportMonitor monitor, + WorkScheduler scheduler, + Connector connector) { + this(monitor, scheduler); + this.connector = connector; + } + + @Property + public void setHttpPort(int httpPort) { + this.httpPort = httpPort; + } + + @Property + public void setHttpsPort(int httpsPort) { + this.httpsPort = httpsPort; + } + + @Property + public void setSendServerVersion(boolean sendServerVersion) { + this.sendServerVersion = sendServerVersion; + } + + @Property + public void setHttps(boolean https) { + this.https = https; + } + + @Property + public void setKeystore(String keystore) { + this.keystore = keystore; + } + + @Property + public void setCertPassword(String certPassword) { + this.certPassword = certPassword; + } + + @Property + public void setKeyPassword(String keyPassword) { + this.keyPassword = keyPassword; + } + + @Property + public void setDebug(boolean val) { + debug = val; + } + + @Init + public void init() throws Exception { + try { + state = STARTING; + server = new Server(); + if (scheduler == null) { + BoundedThreadPool threadPool = new BoundedThreadPool(); + threadPool.setMaxThreads(100); + server.setThreadPool(threadPool); + } else { + server.setThreadPool(new TuscanyThreadPool()); + } + if (connector == null) { + if (https) { + Connector httpConnector = new SelectChannelConnector(); + httpConnector.setPort(httpPort); + SslSocketConnector sslConnector = new SslSocketConnector(); + sslConnector.setPort(httpsPort); + sslConnector.setKeystore(keystore); + sslConnector.setPassword(certPassword); + sslConnector.setKeyPassword(keyPassword); + server.setConnectors(new Connector[]{httpConnector, sslConnector}); + } else { + SelectChannelConnector selectConnector = new SelectChannelConnector(); + selectConnector.setPort(httpPort); + server.setConnectors(new Connector[]{selectConnector}); + } + } else { + connector.setPort(httpPort); + server.setConnectors(new Connector[]{connector}); + } + ContextHandler contextHandler = new ContextHandler(); + contextHandler.setContextPath(ROOT); + server.setHandler(contextHandler); + servletHandler = new ServletHandler(); + contextHandler.setHandler(servletHandler); + server.setStopAtShutdown(true); + server.setSendServerVersion(sendServerVersion); + monitor.started(); + server.start(); + state = STARTED; + } catch (Exception e) { + state = ERROR; + throw e; + } + } + + @Destroy + public void destroy() throws Exception { + state = STOPPING; + synchronized (joinLock) { + joinLock.notifyAll(); + } + server.stop(); + state = STOPPED; + monitor.shutdown(); + } + + public void registerMapping(String path, Servlet servlet) { + ServletHolder holder = new ServletHolder(servlet); + servletHandler.addServlet(holder); + ServletMapping mapping = new ServletMapping(); + mapping.setServletName(holder.getClassName()); + mapping.setPathSpec(path); + servletHandler.addServletMapping(mapping); + } + + public void unregisterMapping(String string) { + throw new UnsupportedOperationException(); + } + + public void registerComposite(File compositeLocation) throws IOException { + throw new UnsupportedOperationException(); + } + + public Server getServer() { + return server; + } + + public int getHttpPort() { + return httpPort; + } + + /** + * An integration wrapper to enable use of a {@link WorkScheduler} with Jetty + */ + private class TuscanyThreadPool implements ThreadPool { + + public boolean dispatch(Runnable job) { + scheduler.scheduleWork(new TuscanyWork(job)); + return true; + } + + public void join() throws InterruptedException { + synchronized (joinLock) { + joinLock.wait(); + } + } + + public int getThreads() { + throw new UnsupportedOperationException(); + } + + public int getIdleThreads() { + throw new UnsupportedOperationException(); + } + + public boolean isLowOnThreads() { + // TODO FIXME + return false; + } + + public void start() throws Exception { + + } + + public void stop() throws Exception { + + } + + public boolean isRunning() { + return state == STARTING || state == STARTED; + } + + public boolean isStarted() { + return state == STARTED; + } + + public boolean isStarting() { + return state == STARTING; + } + + public boolean isStopping() { + return state == STOPPING; + } + + public boolean isFailed() { + return state == ERROR; + } + } + + /** + * A unit of work dispatched to the runtime work scheduler + */ + private class TuscanyWork implements Work { + + Runnable job; + + public TuscanyWork(Runnable job) { + this.job = job; + } + + public void release() { + } + + public void run() { + job.run(); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/TransportMonitor.java b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/TransportMonitor.java new file mode 100644 index 0000000000..c68eacd21c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/main/java/org/apache/tuscany/service/jetty/TransportMonitor.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.jetty; + +/** + * The monitoring interfaces used by the Jetty system service + * + * @version $$Rev$$ $$Date$$ + */ +public interface TransportMonitor { + + /** + * Called after the service is initialized + */ + void started(); + + /** + * Called after the service is stopped + */ + void shutdown(); + + void warn(String msg, Object...args); + + void debug(String msg, Object...args); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/test/java/org/apache/tuscany/service/jetty/JettyServiceImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/test/java/org/apache/tuscany/service/jetty/JettyServiceImplTestCase.java new file mode 100644 index 0000000000..987d7d9a16 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/services/transports/http.jetty/src/test/java/org/apache/tuscany/service/jetty/JettyServiceImplTestCase.java @@ -0,0 +1,173 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.service.jetty; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.Socket; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.tuscany.spi.services.work.WorkScheduler; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class JettyServiceImplTestCase extends TestCase { + + private static final String REQUEST1_HEADER = + "GET / HTTP/1.0\n" + + "Host: localhost\n" + + "Content-Type: text/xml\n" + + "Connection: close\n" + + "Content-Length: "; + private static final String REQUEST1_CONTENT = + ""; + private static final String REQUEST1 = + REQUEST1_HEADER + REQUEST1_CONTENT.getBytes().length + "\n\n" + REQUEST1_CONTENT; + + private static final int HTTP_PORT = 8585; + + private TransportMonitor monitor; + private WorkScheduler scheduler; + private ExecutorService executor = Executors.newCachedThreadPool(); + + /** + * Verifies requests are properly routed according to the servlet mapping + */ + public void testRegisterServletMapping() throws Exception { + JettyServiceImpl service = new JettyServiceImpl(monitor); + service.setHttpPort(HTTP_PORT); + service.init(); + TestServlet servlet = new TestServlet(); + service.registerMapping("/", servlet); + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + service.destroy(); + assertTrue(servlet.invoked); + } + + public void testUseWorkScheduler() throws Exception { + JettyServiceImpl service = new JettyServiceImpl(monitor, scheduler); + service.setDebug(true); + service.setHttpPort(HTTP_PORT); + service.init(); + TestServlet servlet = new TestServlet(); + service.registerMapping("/", servlet); + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + service.destroy(); + assertTrue(servlet.invoked); + } + + public void testRestart() throws Exception { + JettyServiceImpl service = new JettyServiceImpl(monitor); + service.setHttpPort(HTTP_PORT); + service.init(); + service.destroy(); + service.init(); + service.destroy(); + } + + public void testNoMappings() throws Exception { + JettyServiceImpl service = new JettyServiceImpl(monitor); + service.setHttpPort(HTTP_PORT); + service.init(); + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + service.destroy(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + //executor.submit(); + } + + protected void setUp() throws Exception { + super.setUp(); + monitor = createMock(TransportMonitor.class); + scheduler = createMock(WorkScheduler.class); + scheduler.scheduleWork(isA(Runnable.class)); + + expectLastCall().andStubAnswer(new IAnswer() { + public Object answer() throws Throwable { + Runnable runnable = (Runnable) getCurrentArguments()[0]; + executor.execute(runnable); + return null; + } + }); + replay(scheduler); + } + + private static String read(Socket socket) throws IOException { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + StringBuffer sb = new StringBuffer(); + String str; + while ((str = reader.readLine()) != null) { + sb.append(str); + } + return sb.toString(); + } finally { + if (reader != null) { + reader.close(); + } + } + } + + private class TestServlet extends HttpServlet { + boolean invoked; + + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + invoked = true; + OutputStream writer = resp.getOutputStream(); + try { + writer.write("result".getBytes()); + } finally { + writer.close(); + } + } + + + } +} |